我知道的重寫方法的情況Java遵循動態綁定。但是如果我們從引用子對象的父引用變量中調用一個僅子方法,就會出現編譯錯誤。
爲什麼java遵循這種設計(即爲什麼沒有第二種情況下的動態綁定)?爲什麼不同的設計爲動態綁定和從父類調用僅子方法?
class A{
public void sayHi(){ "Hi from A"; }
}
class B extends A{
public void sayHi(){ "Hi from B";
public void sayGoodBye(){ "Bye from B"; }
}
main(){
A a = new B();
//Works because the sayHi() method is declared in A and overridden in B. In this case
//the B version will execute, but it can be called even if the variable is declared to
//be type 'A' because sayHi() is part of type A's API and all subTypes will have
//that method
a.sayHi();
//Compile error because 'a' is declared to be of type 'A' which doesn't have the
//sayGoodBye method as part of its API
a.sayGoodBye();
// Works as long as the object pointed to by the a variable is an instanceof B. This is
// because the cast explicitly tells the compiler it is a 'B' instance
((B)a).sayGoodBye();
}
但在運行時,它遵循動態綁定。 意思是我可以說爲了調用'a.sayHi()'編譯嘗試在A中找到'sayHi()'sayHi()'聲明並且它存在於那裏,所以沒有錯誤。然後在運行時根據對象(即內存地址)調用東西,並且存在C的sayHi()的定義,所以它被調用。 對於方法'sayGoodbye',當你在編譯時得到錯誤(正如你所解釋的),應該沒有問題是在運行時調用哪個定義。 –
@knoxxs。是的。在代碼甚至不編譯時,在運行時沒有行爲問題。 –