package com.apple;
class NoteX{
public static final int
MIDDLE_C=0,C_SHARP=1,C_FLAT=2;
}
class InstrumentX{
public void play(int NoteX){
System.out.println("InstrumentX.paly()");
}
}
class WindX extends InstrumentX{
public void play(NoteX n){
System.out.println("WindX.play(NoteX n)");
}
}
public class WindError {
public static void tune(InstrumentX i){
i.play(NoteX.MIDDLE_C);
}
public static void main(String[] args){
WindX flute=new WindX();
tune(flute);
}
}
这里首先需要讲的是另一个容易混淆的概念。在InstrumentX中play()方法采用了一个int(整数)数值,他的标识符是NoteX。也就是说,及时NoteX是一个类名,也可以把它作为一个标识符来使用,编译器不会报告错误。但是在WindX中,play()采用一个Notex句柄,它有一个标识符n。
即便我们使用“play(NoteX NoteX)”,编译器也不会报告错误。这样一来,看起来就像是程序员有意覆盖play()的功能,但对方法的类型定义却稍微有些不确定。然而,编译器此时假定的是程序员有意进行“过载”而不是“覆盖”。
过载:指的是同一样东西在不同的地方具有许多种含义;
覆盖:指的是它随时随地都只有一种含义,只是原先的含义完全被替代了。
在tune中,“InstrumentX i”会发出play()的消息,同时将某个NoteX成员作为自变量使用(MODDLE_C)。由于NoteX包含了int定义,过载的play()方法的Int版本会得到调用。同时由于它未被覆盖,所以会使用基础类的版本。
输出结果是:
InstrumentX.paly()