在这种情况下,为什么调用父类方法而不是子类方法?

Pra*_*h P 4 java inheritance

我有一个父类 A 和它的子类 B。两者都有具有doSomething不同类型参数的方法。

A级

package Inheritance;

public class A {

    public void doSomething(Object str){
        System.out.println("Base impl:"+str);
    }
}
Run Code Online (Sandbox Code Playgroud)

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");

    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到“Base impl:override”作为输出!

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

Era*_*ran 5

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

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