如果我已经完成了向上转换,为什么要从子类调用重写方法?

2022-01-24 00:00:00 inheritance polymorphism java upcasting

我刚开始学习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.

相关文章