java-调用超类方法而不是子类方法

让我们看一下这段代码:

public class ParentClass {
    public void foo(Object o) {
        System.out.println("Parent");
    }
}

public class SubClass extends ParentClass {
    public void foo(String s) {
        System.out.println("Child");
    }

    public static void main(String args[]) {
        ParentClass p = new SubClass();
        p.foo("hello");
    }
}

我希望这能打印出“孩子”,但结果是“父母”.为什么Java会改为调用父类,我该怎么做才能使其在子类中调用方法?

解决方法:

SubClass#foo()不会覆盖ParentClass#foo(),因为它没有相同的形式参数.一个使用Object,另一个使用String.因此,运行时的多态不会被应用,并且不会导致子类方法的执行.从Java Language Specification

An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:

  • A is a superclass of C.

  • C does not inherit mA.

  • The signature of mC is a subsignature (§8.4.2) of the signature of mA.

并且this section定义了方法签名:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

  • m2 has the same signature as m1, or

  • the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

上一篇:6 pandas人口分析案例


下一篇:PHP登录验证之间有区别吗