why overridden method calling from Subclass if i have done up-casting?(如果我已经完成了向上转换,为什么要从子类调用重写方法?)
问题描述
我刚开始学习java::Inheritance,在混合Up-Casting时感到困惑.
i have just started learning java::Inheritance and confused while mixing Up-Casting.
class Example{
public void methodOne(){
System.out.println("Example::Method_1");
}
public void methodTwo(){
System.out.println("Example::Method_2");
}
}
public class Test extends Example{
public void methodTwo(){ //Method overriding
System.out.println("Test::Method_2");
}
public void methodThree(){
System.out.println("Test::Method_3");
}
public static void main(String[] args){
Example exa = new Test(); // UpCasting
exa.methodOne(); // Printing Example::Method_1
exa.methodTwo(); // Printing Test::Method_2
// exa.methodThree(); // Error : can not find symbol
}
}
谁能解释一下,这里发生了什么?
may someone please explain, what happening here??
推荐答案
使用继承时,对调用方法的对象的引用的编译时类型仅用于查看(在编译时)是否方法可能会被调用.
When using inheritance, the compile-time type of the reference to an object on which you call a method is only used to see (at compile time) if the method may be invoked.
但是在调用时,编译时类型是什么并不重要.在这种情况下,真正重要的是对象的运行时类型.是Test
,所以先在Test
上搜索方法
But at the invocation time, it does not matter what that compile-time type is. What really matters in this case is the runtime type of the object. It is Test
, so the method is searched on Test
first.
对于 methodOne()
有点不同:它不会被 Test
覆盖,因此它的超类的版本(Example
)被调用.
For methodOne()
it is a bit different: it is not overriden by Test
, so the version from its superclass (Example
) is invoked.
这篇关于如果我已经完成了向上转换,为什么要从子类调用重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果我已经完成了向上转换,为什么要从子类调用重写方法?


- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01