1. 代码示例
package demo01; class Grain { @Override public String toString() { return "Grain []"; } } class Wheat extends Grain { @Override public String toString() { return "Wheat []"; } } class Mill { Grain process() { return new Grain(); } } class WheatMill extends Mill { @Override Grain process() { return new Wheat(); } } public class Poppet { public static void main(String[] args) { Mill m = new WheatMill(); System.out.println(m.process()); } }
2.解析
如代码所示,基类方法的返回类型如果也是基类的话,子类重写的方法可以返回基类的子类.表示子类重写方法的返回值可以是基类方法返回值的子类型.
标签:返回,return,子类,协变,public,Grain,基类,类型,class From: https://www.cnblogs.com/lishuaiqi/p/16786509.html