转换到超类,并调用覆盖方法 [英] Casting to Superclass, and Calling Overriden Method

查看:23
本文介绍了转换到超类,并调用覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个问题.我扩展了一个类 Parrent 并在 Child 类中覆盖了它的一个方法.我试图将类型转换为超类类型,但我每次都得到孩子的重写方法.当我使用多态时也会发生这种情况.

I have my next question. I have extended a class, Parrent and overridden one of its method in the Child class. I tried to cast the type to the superclass type, but I get the child's overridden method every time. This also happens when I use polymorphism.

问题在下面代码中的注释中...提前致谢.

Questions are in the comments inside code below... Thanks in advance.

class Parrent{
    public void test(){
        System.out.println("parentTest"); 
    }
}

class Child extends Parrent{
    @Override
    public void test(){
        System.out.println("childTest");
    }
}

class StartProgram{
    public static void main(String[] args) {
        Parrent p1 = new Parrent();
        p1.test(); // output: parentTest

        Child c1 = new Child();
        c1.test(); // output: childTest

        Parrent p2 = new Child();
        p2.test(); // why returns child method? becouse it's overriden?

        ((Parrent) new Child()).test();  // why returns child method if I cast it?

    }
}

推荐答案

强制转换只是为了编译器的利益.JVM 对此一无所知,也不影响调用什么方法.JVM 尝试通过查找与给定签名匹配的内容来解析方法,从最具体的类开始,并在层次结构中朝根 (java.lang.Object) 向上移动,直到找到某些内容.

Casting is solely for the benefit of the compiler. The JVM doesn't know anything about it, and it does not affect what method gets called. The JVM tries to resolve a method by looking for something that matches the given signature, starting with the most specific class and working its way up the hierarchy towards the root (java.lang.Object) until it finds something.

多态的目的是让调用某个对象的代码不必确切地知道正在使用什么子类,被调用的对象会负责自己的特殊功能.让子类覆盖一个方法意味着该子类的对象需要以自己特定的方式处理该方法,而调用者不必关心它.

The purpose of polymorphism is so code calling some object doesn't have to know exactly what subclass is being used, the object being called takes care of its own specialized functionality. Having a subclass override a method means that objects of that subclass need to handle that method in their own particular way, and the caller doesn't have to care about it.

强制转换适用于您的代码不知道某事物是什么类型的奇怪边缘情况.如果您知道超类型(在您的示例中为 Parent),则不需要强制转换,子类应该自行处理.

Casting is for odd edge cases where your code can't know what type something is. You shouldn't need to cast if you know the super type (Parent in your example), the subclass should take care of itself.

这篇关于转换到超类,并调用覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆