问题描述
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.why我不能接受变量通过aObj虽然它是引用类B ??
2.为什么我能够接受方法show()?
In the above program i'm getting Error wen i try invoking aObj.b.
1.why i'm not able to acess that variable through the aObj though it is refering to class B??
2. why i'm able to acess the method show()?
推荐答案
您必须区分 static type aObj 和 c c>
You have to distinguish between the static type of aObj and the runtime type of aObj.
的运行时类型
A aObj = new B();
会产生具有静态类型的 aObj 变量 A 和运行时类型 B 。
results in an aObj variable with static type A and runtime type B.
回答您的问题:
因为(通常)编译器没有办法知道 aObj 会引用a B 对象,只是它将引用某种形式的 A 对象。由于 .b 不适用于所有 A 对象,因此编译器会认为 并禁止它。
Because there is (in general) no way for the compiler to know that aObj will refer to a B object at runtime, only that it will refer to some form of A object. Since .b is not available on all A objects, so the compiler will think "better safe than sorry" and disallow it.
因为此方法 在所有 A 对象(如果它没有在子类中声明,它仍然继承自 A )。
Because this method is available in all A objects (if it's not declared in the subclass, it is still inherited from A).
这篇关于Java中的动态方法分派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!