我刚刚开始学习 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
上搜索方法。
对于 methodOne()
它有点不同:它没有被 Test
覆盖,所以它的父类(super class)版本(Example
)被调用。
关于java - 如果我已经完成向上转换,为什么要重写从子类调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660541/