I encountered an issue while playing around with Java class inheritance, where subclass C has a method fun() like its parent A, but different signature. However I do not understand why the parent class's method is called when fun() is invoked on object x. I do understand that because signature is different this is not exactly method overriding, but i still do not understand why A's fun() method is invoked here.
class A
class A{
public void fun(double d){
System.out.println("A");
}
}
class C
public class C extends A{
public static void main(String[] args){
A x = new C();
x.fun(6); //prints "A"
}
public void fun(int i){
System.out.println("C");
}
}
Here:
A x = new C();
The compiler only remembers: x is of class A. So when you do:
x.fun(6); //prints "A"
it looks up the methods that exist in A. There is only one named fun()
, and that one is taking a double. So the compiler puts method call to fun(double)
into the bytecode. The fact that later, at runtime, x also has a method taking an int doesn't matter. Because at compile time, fun(double)
was "pinned" so to say.
If you want to get to the polymorphic experience, change the type of foo()
in C to also take double, so: make it a true override. Or change the definition to C x = ...
. Then it will print "C".
That is all there is to this.