A superclass method is called instead of the subclass method

后端 未结 3 546
庸人自扰
庸人自扰 2020-12-11 19:25

Let\'s take a look at this code:

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

public class Sub         


        
相关标签:
3条回答
  • 2020-12-11 20:07

    The parent class has no method with the signature public void foo(String s). Therefore, at compile time, the compiler can only choose the public void foo(Object o) method for executing p.foo("hello").

    Since the child class doesn't override this method (it doesn't have the same parameter type), the parent class's foo method is the one executed at runtime.

    0 讨论(0)
  • 2020-12-11 20:10

    Strings are objects in java, as said its not overridden but as you pass a string it will run the first available method that can the the argument, in this case it is the super-class's method.

    0 讨论(0)
  • 2020-12-11 20:24

    SubClass#foo() does not override ParentClass#foo() because it doesn't have the same formal parameters. One takes Object and the other takes a String. Therefore polymorphism at runtime is not applied and does not cause the subclass method to execute. From the 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.

    ...

    And this section defines method signatures:

    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.

    0 讨论(0)
提交回复
热议问题