class A{
int a=10;
public void show(){
System.out.println("Show A: "+a);
}
}
class B extends A{
public int b=20;
public void show(){
System.out.println("Show B: "+b);
}
}
public class DynamicMethodDispatch {
public static void main(String[] args) {
A aObj = new A();
aObj.show(); //output - 10
B bObj = new B();
bObj.show(); //output - 20
aObj = bObj; //assigning the B obj to A..
aObj.show(); //output - 20
aObj = new B();
aObj.show(); //output - 20
System.out.println(bObj.b); //output - 20
//System.out.println(aObj.b); //It is giving error
}
}
在上面的程序中,我尝试调用 aObj.b 时遇到错误。
1.为什么我无法通过 aObj 访问该变量,尽管它指的是 B 类?
2. 为什么我可以访问 show() 方法?
最佳答案
您必须区分aObj
的静态类型 和aObj
的运行时类型。
代码如
A aObj = new B();
产生一个 aObj
静态类型 A
和运行时类型 B
的变量。
编译器在决定允许或不允许什么时只会费心查看静态类型。
您的问题:
1.why i'm not able to acess that variable through the aObj though it is refering to class B??
因为(通常)编译器无法知道 aObj
将在运行时引用 B
对象,仅它将引用某种形式的 A
对象。由于 .b
并非在所有 A
对象上都可用,因此编译器会认为“安全总比抱歉好” 并禁止它。
2.why i'm able to acess the method show()?
因为这个方法是在所有A
对象中都可用(如果没有在子类中声明,它仍然继承自A
)。
关于java - java中的动态方法调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10595527/