Avi*_*mar 4 java polymorphism inheritance upcasting
我刚刚开始学习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
}
}
Run Code Online (Sandbox Code Playgroud)
也许有人请解释一下,这里发生了什么?
使用继承时,对您调用方法的对象的引用的编译时类型仅用于查看(在编译时)是否可以调用该方法.
但是在调用时,编译时类型是什么并不重要.在这种情况下真正重要的是对象的运行时类型.它是Test,所以Test首先搜索该方法.
因为methodOne()它有点不同:它没有被覆盖Test,因此Example调用其超类()的版本.
| 归档时间: |
|
| 查看次数: |
1204 次 |
| 最近记录: |