我刚刚开始学习 java::Inheritance,并且在混合 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
}
}
有人可以解释一下,这里发生了什么?
使用继承时,对调用其方法的对象的引用的编译时类型仅用于查看(在编译时)是否可以调用该方法。
但在调用时,编译时类型是什么并不重要。在这种情况下真正重要的是对象的运行时类型。这是Test
,所以该方法在Test
first.
For methodOne()
它有点不同:它不会被覆盖Test
,因此来自其超类的版本(Example
) 被调用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)