I do not understand this Java behavior. I have two classes:
class C1 {
public void m1(double num) {
System.out.println(\"Inside C1.m1(): \" + num
The reason why you see the output as Inside C1.m1(): 10.0
and not Inside C1.m1(): 10
or Inside C2.m1(): 10.0
is because :
m1
in C2
. You are overloading the m1(doube)
method that you inherited from C1
to m1(int)
instead.C2
class now has two m1
methods. One that is inherited
from C1
and has the signature m1(double)
and one that is overloaded in C2
and has the signature m1(int)
c.m1(10)
, it resolves this call based on the reference type. Since the reference type is C1
, the compiler is going to resolve this call to m1(double)
in C1
. m1(double)
in C2
which is the method inherited from C1
. (As explained in point 2)There are two ways in which the m1(int)
method can be called :
((C2)c).m1(10);
OR
C2 c = new C2();
c.m1(10);