//:c07:winderror.java
//Accidentally changing the interface.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.play()");
}
}class WindX extends InstrumentX{
//OOPS!Changes the method interface:
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);//Not the desired behavior;
}
}///:-
//结果输出的是:
InstrumentX.play()
为什么不是:
WindX.play(NoteX n)

解决方案 »

  1.   

    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.play()");
    }
    }class WindX extends InstrumentX{
    //OOPS!Changes the method interface:
    public void play( NoteX n){
    System.out.println("WindX.play(NoteX n)");
    }
    }public class WindError{
    public static void tune(WindX i){ //参数类型应该为: WindX 
    //...
    i.play(NoteX.MIDDLE_C);
    }
    public static void main(String []args){
    WindX flute = new WindX();
    tune(flute);//Not the desired behavior;
    }
    }
      

  2.   

    tune中的参数i是InstrumentX类型的引用,传参时他引用了WindX 类型的对象,这是合法的。  i.play(NoteX.MIDDLE_C);中的NoteX.MIDDLE_C是int型的,那么i就会调用play(int NoteX)方法,而不是play( NoteX n)。  这是方法的重载,相当于i所引用的WindX 类型的对象有两个play方法,一个是继承而来的,另一个是自己定义的,两者参数列表不同,不是方法的覆盖(或重写),根据实参的类型来选择调用那个方法。  不知道说没说明白。
      

  3.   

    edward0716(雲威龍),你的修改方法试过吗?我觉得这样该不会改变输出结果。
      

  4.   

    楼上说的对,很详细了。
    WindX类型他继承了InstrumentX自然有public void play(int NoteX)方法,自己又新加方法
    public void play( NoteX n),即重载。系统自己会根据参数选择调用哪个方法。