我知道对于覆盖方法的情况,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();
}