java中动态方法,Java中的动态方法分派

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

}

}

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()?

解决方案

You have to distinguish between the static type of aObj and the runtime type of aObj.

Code such as

A aObj = new B();

results in an aObj variable with static type A and runtime type B.

The compiler will only bother too look at the static type when deciding what to allow or not.

To your questions:

1.why i'm not able to acess that variable through the aObj though it is refering to class B??

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.

2.why i'm able to acess the method show()?

Because this method is available in all A objects (if it's not declared in the subclass, it is still inherited from A).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值