ThinkingInJava第八章多态

多态的条件:继承(向上转型),方法的重写,导出类指向基类

Shape s = new Circle();

由于后期绑定(多态)当我们调用s.say();的方法是调用的Circle类的对Shape继承或者实现的say方法。

优点:可扩展性

class Grain{
    @Override
    public String toString() {
        return "Grian";
    }
}
class Wheat extends Grain{
    @Override
    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.print(g);
        m=new WheatMill();
        g=m.process();
        System.out.print(g);
    }
}

输出 Grain Wheat

协变返回值

 

posted @ 2018-08-19 15:43  森海大鲸鱼  阅读(118)  评论(0)    收藏  举报