Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A superclass method is called instead of the subclass method

Let's take a look at this code:

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

I expected this to print out "Child", but the result is "Parent". Why does java call the super class instead, and what do I do to make it call the method in the subclass?

like image 602
user2979612 Avatar asked Oct 20 '22 07:10

user2979612


1 Answers

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.

like image 186
M A Avatar answered Oct 27 '22 00:10

M A