java - A superclass method is called instead of the subclass method -


let's take @ 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 print out "child", result "parent". why java call super class instead, , do make call method in subclass?

subclass#foo() not override parentclass#foo() because doesn't have same formal parameters. 1 takes object , other takes string. therefore polymorphism @ runtime not applied , not cause subclass method execute. java language specification:

an instance method mc declared in or inherited class c, overrides c method ma declared in class a, iff of following true:

  • a superclass of c.

  • c not inherit ma.

  • the signature of mc subsignature (§8.4.2) of signature of ma.

...

and this section defines method signatures:

two methods or constructors, m , n, have same signature if have same name, same type parameters (if any) (§8.4.4), and, after adapting formal parameter types of n the type parameters of m, same formal parameter types.

the signature of method m1 subsignature of signature of method m2 if either:

  • m2 has same signature m1, or

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


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -