如果我已完成向上转换,为什么要从子类重写方法调用? [英] 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.
这篇关于如果我已完成向上转换,为什么要从子类重写方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!