《Thing in java》上塑造型的笔记

来源:互联网 发布:在淘宝上搜春药怎么搜 编辑:程序博客网 时间:2024/06/01 09:35
//: Music.java// Inheritance & upcastingclass Note {    private int value;    private Note(int val) {        value = val;    }    public static final Note            middleC = new Note(0),            cSharp = new Note(1),            cFlat = new Note(2);} // Etc.class Instrument {    public void play(Note n) {        System.out.println("Instrument.play()");    }}// Wind objects are instruments// because they have the same interface:class Wind extends Instrument {    // Redefine interface method:    public void play(Note n) {        System.out.println("Wind.play()");    }}public class Music {    public static void tune(Instrument i) {        // ...        i.play(Note.middleC);    }    public static void main(String[] args) {        Wind flute = new Wind();        tune(flute); // Upcasting    }} ///:~

其中,方法 Music.tune()接收一个Instrument 句柄,同时也能接收从Instrument 衍生出来的所有东西。当一个Wind 句柄传递给 tune()的时候,就会出现这种情况。此时没有造型的必要。这样做是可以接受的;
Instrument 里的接口必须存在于 Wind 中,因为Wind 是从Instrument 里继承得到的。从 Wind 向Instrument的上溯造型可能“缩小”那个接口,但不可能把它变得比 Instrument 的完整接口还要小。

阅读全文
0 0
原创粉丝点击