java - Calling overloaded inherited methods using super class reference -
i not understand java behavior. have 2 classes:
class c1 { public void m1(double num) { system.out.println("inside c1.m1(): " + num); } } class c2 extends c1 { public void m1(int num) { system.out.println("inside c2.m1(): " + num); } }
and main:
public class main { public static void main(string[] args) { c1 c = new c2(); c.m1(10); } }
and result was:
inside c1.m1(): 10.0
when expected:
inside c2.m1(): 10
also when try complete code syntax, found this:
where other m1 of c2 class?
i check bytecode of main.class , saw this:
compiled "main.java" public class com.company.main { public com.company.main(); code: 0: aload_0 1: invokespecial #1 // method java/lang/object."<init>":()v 4: return public static void main(java.lang.string[]); code: 0: new #2 // class com/company/c2 3: dup 4: invokespecial #3 // method com/company/c2."<init>":()v 7: astore_1 8: aload_1 9: ldc2_w #4 // double 10.0d 12: invokevirtual #6 // method com/company/c1.m1:(d)v 15: return }
the bytecode tell me invoke c1.m1 (d)v (line 12).
why method of c1? trying understand behavior.
your 2 methods named m1
not have same signature; 1 in superclass takes double
, , 1 in subclass takes int
. means compiler select method signature call based on compile-time type of variable, c1
, , call m1(double)
. since @ runtime class c2
doesn't have overriding version of m1(double)
, version c1
invoked.
the rule method signatures computed @ compile time based on compile-time types; method calls dispatched @ runtime based on matching signatures.
Comments
Post a Comment