Welcome

首页 / 软件开发 / JAVA / 上溯造型的问题

上溯造型的问题2007-05-28 yycnet.yeah.net yyc译在第6章,大家已知道可将一个对象作为它自己的类型使用,或者作为它的基础类型的一个对象使用。取得一个对象句柄,并将其作为基础类型句柄使用的行为就叫作“上溯造型”——因为继承树的画法是基础类位于最上方。
但这样做也会遇到一个问题,如下例所示(若执行这个程序遇到麻烦,请参考第3章的3.1.2小节“赋值”):

//: Music.java // Inheritance & upcastingpackage c07;class Note {private int value;private Note(int val) { value = val; }public static final NotemiddleC = 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的完整接口还要小。