在Java中,为什么((A)b).disp()调用派生类方法disp()而不是基类方法disp()?

编程入门 行业动态 更新时间:2024-10-15 20:25:34
本文介绍了在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()?

本文发布于:2023-08-04 09:09:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1294988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   而不是   派生类   Java   disp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!