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

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.

这篇关于如果我已经完成了向上转换,为什么要从子类调用重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐