在Java中,为什么((A)b).disp()调用派生类方法disp()而不是基类方法disp()? [英] In Java, why does ((A)b).disp() call derived class method disp() instead of base class method disp() ?

查看:71
本文介绍了在Java中,为什么((A)b).disp()调用派生类方法disp()而不是基类方法disp()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,是一个初学者...请帮助我找出为什么它不起作用...

I am learning Java, am a beginner... Please help me out finding why this is not working...

在下面的程序中,我的目标是从主方法调用基类方法,而在派生类方法中不使用super关键字.

In the following program, my aim is to call base class method from main method, without using super keyword in derived class method.

如代码中所示,main方法中的((A)b).num可以很好地工作,并且按预期输出100,但是((A)b).disp()输出B方法中的内容,而不是的方法.

As shown in the code, ((A)b).num in main method works perfectly fine, and ouputs, 100 as expected, but ((A)b).disp() outputs the contents in B's method, instead of A's method.

class A
{
    int num=100;

    public void disp()
    {
    System.out.println("Disp() of A:");
    System.out.println(num);
    }

}

class B extends A
{
    int num=200;

    public void disp()
    {
    System.out.println("Disp() of B:");
    super.disp();              //100
    System.out.println( num );  //200
    }

}

class ques
{

    public static void main(String a[])
    {
    B b=new B();

    b.disp();         

    System.out.println();
    ((A)b).disp();                          //doesn't work

    System.out.println();
    System.out.println(((A)b).num);         //works
    }

}

输出为:

Disp() of B:
Disp() of A:
100
200

Disp() of B:
Disp() of A:
100
200
100

但是我的预期输出是:

Disp() of B:
Disp() of A:
100
200


Disp() of A:
100

100

任何人都可以帮助我找到此输出的原因.

Can anyone please help me find the reason for this output.

为什么((A)b).num可以正常工作并且((A)b).disp()不能按预期方式工作...

Why ((A)b).num is working fine and ((A)b).disp() not working as expected...

此外,这不会产生编译错误.在此先感谢..:)

Moreover this doesn't give compile error.... !! Thanks in advance.. :)

推荐答案

必须使用这种方法来保留派生类的语义.

It must be this way to preserve the semantics of the derived class.

想象一下A具有一个整数属性名称​​ value ,而A.alter()是一种更改该值的方法.想象一下,B扩展了A并覆盖了该方法,B进一步保证了属性 value 始终为正.A.alter()有时可能会导致该值为负,但B.alter()永远不会.

Imagine A has an integer attribute name value, and A.alter() is a method that changes that value. Imagine B extends A and overrides that method, and B gives the additional guarantee that the attribute value is always positive. A.alter() might sometimes cause the value to be negative, but B.alter() never will.

如果((A)b).alter()在类型B的对象上调用了A.alter()方法,则结果可能是具有负值的B:本应保证B具有的保证坏了.

If ((A)b).alter() called the A.alter() method on an object of type B, the result could be a B that had a negative value: the guarantee that B is supposed to have would be broken.

这篇关于在Java中,为什么((A)b).disp()调用派生类方法disp()而不是基类方法disp()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆