一個非常神祕的多態性問題:動態方法綁定異常?
import static java.lang.System.*
class Super{
public void meth(Super other){
out.println("#1 - in Super.meth(Super)");
}
}
class Sub extends Super{
public void meth(Super other){
out.println("#2 - in Sub.meth(Super)");
}
public void meth(Sub other){
out.println("#3 - in Sub.meth(Sub)");
}
}
public class MethodTest{
public static void main(String[] args){
Super sup = new Super();
Sub sub = new Sub();
Super sup_ref_sub = new Sub();
sup_ref_sub.meth(sub);
}
}
有了上面的代碼,我的輸出是「#2 - in Sub.meth(Super)
」,而我所期待的「#3 - in Sub.meth(Sub)
」,更奇怪的是,當我註釋掉<public void meth(Super other){...}>
,輸出改爲「#1 - in Super.meth(Super)
」。