Java 协变返回类型

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

//: 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
*///:~

 

posted @ 2018-12-31 18:04  江期玉  阅读(337)  评论(0编辑  收藏  举报