本文介绍了在这种情况下,为什么要调用父类方法而不是子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类A,它的子类B.两个都具有doSomething方法,且参数类型为diff.

I have a parent class A, and its child B. Both are having doSomething method with diff type of parameters.

A级

package Inheritance;

public class A {

    public void doSomething(Object str){
        System.out.println("Base impl:"+str);
    }
}

B级

package Inheritance;

public class B extends A{

    public void doSomething(String str){
        System.out.println("Child impl:"+str);
    }

    public static void main(String[] args) {

        A a = new B();
        a.doSomething("override");

    }
}

运行此命令时,我得到"Base impl:override"作为输出!

When I run this, I'm getting "Base impl:override" as the output!

a指向B的对象,而他传递的参数是String,那么它不应该调用BdoSomething(String str)方法吗?

a is pointing to an object of B, and the he passed argument is String, So shouldn't it call B's doSomething(String str) method?

推荐答案

使用类型A的引用时,您只会看到为类A定义的方法.由于B中的doSomething不会覆盖doSomething在A中(因为它具有不同的签名),因此不会调用它.

When you are using a reference of type A, you see only the methods defined for class A. Since doSomething in B doesn't override doSomething in A (since it has a different signature), it is not called.

如果要使用类型B的引用,则这两种方法均可用,并且会选择B的doSomething,因为它具有更具体的参数(字符串与对象).

If you were to use a reference of type B, both methods would be available, and doSomething of B would be chosen, since it has a more specific argument (String vs Object).

这篇关于在这种情况下,为什么要调用父类方法而不是子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 20:57