Java 协变返回类型

时间:2022-03-05 22:28:29

协变返回类型表示在导出类的被覆盖方法可以返回基类方法的返回类型的某种导出类型

//: polymorphism/covarianreturn.java

package object;

class Grain{
public String toString()
{
return "Grain";//返回
}
}
class Wheat extends Grain{
public String toString()
{
return "Wheat"; //返回
}
}
class Mill{
Grain process()
{
return new Grain();
}
}
class WheatMill extends Mill{
Wheat process(){return new Wheat();}
}
public class CovariantReturn{
public static void main(String[] args)
{
Mill m = new Mill();
Grain g = m.process();
System.out.println(g);
m = new WheatMill();
g = m.process();
System.out.println(g);
}
}/* output
Grain
Wheat
*///:~