1.何为上溯造型?
package c07;
class 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);
}
class Instrument{
public void play(Note n){
System.out.println("Instrument.play()");
}
}
class Wind extends Instrument{
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);//原方法tune中的参数应该是一个Instrument类型的,现在用它的子类的对象flute作为方法tune的参数。说明对 象lute发生了句柄的转换,转换成了超类Instrument的句柄。
}
}
如以上程序,发生了子类句柄转化为父类句柄的情况,就称为上溯造型。
2.为何要进行上溯造型?
这个程序看起来也许显得有些奇怪。为什么所有人都应该有意忘记一个对象的类型呢?进行上溯造型时,就可能产生这方面的疑惑。而且如果让 tune()简单地取得一个 Wind 句柄,将其作为自己的自变量使用,似乎会更加简单、直观得多。但要注意:假如那样做,就需为系统内Instrument 的每种类型写一个全新的tune()。假设按照前面的推论,加入 Stringed(弦乐)和 Brass(铜管)这两种 Instrument(乐器):
package c07;
class Note2{
private int value;
private Note2(int val){
value = val;
}
public static final Note2 middleC = new Note2(0), cSharp = new Note2(1), cFlat = new Note2(2);
}
class Instrument2{
public void play(Note2 n){
System.out.println("Instrument2.play()");
}
}
class Wind2 extends Instrument2{
public void play(Note2 n){
System.out.println("Wind2.play()");
}
}
class Stringed2 extends Instrument2{
public void play(Note2 n){
System.out.println("Stringed2.play()");
}
}
class Brass2 extends Instrument2{
public void play(Note2 n){
System.out.println("Brass2.play()");
}
}
public class Music2 {
public static void tune(Wind2 i){
i.play(Note2.middleC);
}
public static void tune(Stringed2 i){
i.play(Note2.middleC);
}
public static void tune(Brass2 i){
i.play(Note2.middleC);
}
public static void main(String args[]){
Wind2 flute = new Wind2();
Stringed2 violin = new Stringed2();
Brass2 frenchHorn = new Brass2();
tune(flute);
tune(violin);
tune(frenchHorn);
}
}
这样做当然行得通,但却存在一个极大的弊端:必须为每种新增的Instrument2 类编写与类紧密相关的方法。这意味着第一次就要求多得多的编程量。以后,假如想添加一个象tune()那样的新方法或者为
Instrument 添加一个新类型,仍然需要进行大量编码工作。此外,即使忘记对自己的某个方法进行过载设
置,编译器也不会提示任何错误。这样一来,类型的整个操作过程就显得极难管理,有失控的危险。
但假如只写一个方法,将基础类作为自变量或参数使用,而不是使用那些特定的衍生类,岂不是会简单得
多?也就是说,如果我们能不顾衍生类,只让自己的代码与基础类打交道,那么省下的工作量将是难以估计
的。