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()方法?
你必须区分静态类型 of aObj
和运行时类型 of aObj
.
代码如
A aObj = new B();
结果是aObj
静态类型变量A
和运行时类型B
.
编译器只会费心去查看静态类型在决定允许或不允许什么时。
对于您的问题:
1.为什么我无法通过 aObj 访问该变量,尽管它引用的是 B 类?
因为(一般来说)编译器没有办法know that aObj
将参考一个B
运行时对象,只是它会引用某种形式A
目的。自从.b
并非适用于所有A
对象,所以编译器会认为“安全总比后悔好”并禁止它。
2.为什么我可以访问show()方法?
因为这个方法is全部可用A
对象(如果没有在子类中声明,它仍然继承自A
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)