在tune()中,程序代码可以对Instrument和它所有的导出类起作用,这种将wind引用转换为instrument引用的动作,我们称之为向上转型.
其实就是在父类里有一个方法规定了可以使用父类类型的对象
在子类里使用父类的这个方法,并传递子类自身作为参数
然后使用这个子类自身对象调用父类里存在的方法
由导出类转型成基类,在继承图上是向上移动的,因此一般称为向上转型。由于向上转型是从一个较专用类型向较通用类型转换,所以总是很安全的。也就是说,导出类是基类的一个超集。它可能比基类含有更多的方法,但它必须至少具备基类中所含有的方法。在向上转型的过程中,类接口中唯一可能发生的事情是丢失方法,而不是获取它们。这就是为什么编译器在“未曾明确表示转型”或“未曾指定特殊标记”的情况下,仍然允许向上转型的原因。
class Instrument {
protected String name;
public Instrument(String name) {
this.name = name;
}
public void play() {
System.out.println("使用 " + this.getClass().getName() + " 演奏了: " + name);
}
static void tune(Instrument i) {
i.play();
}
}
public class Wind extends Instrument {
public Wind(String name) {
super(name);
}
public static void main(String[] args) {
Wind flute = new Wind("《一千年以后》");
Instrument.tune(flute);
}
}