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 methodma
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 ofma
....
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 methodm2
if either:
m2
has same signaturem1
, orthe signature of
m1
same erasure (§4.6) of signature ofm2
.
Comments
Post a Comment