As per my knowledge if a method is non - static and non - private, then invokevirtual instructions are added in the bytecode which results in dynamic binding at runtime, but in the following program why the compile time binding is being done.
class Fruit{
}
class Apple extends Fruit{
}
class MyTest{
public void show(Fruit f){
System.out.println("fruit");
}
public void show(Apple a){
System.out.println("apple");
}
public static void main(String[] args) {
MyTest t = new MyTest();
Fruit f = new Fruit();
t.show(f);
Apple a = new Apple();
t.show(a);
Fruit f1 = new Apple();
t.show(f1);
}
}
The output of the following program is
Fruit
Apple
Fruit
I have a doubt in this following line of code
Fruit f1 = new Apple();
t.show(f1);
because show() is an instance method which results in invokevirtual and in case of invokevirtual, the late binding is done based on the type of object, so accordingly it should print "Apple", then why the result is "Fruit" which is based on type of reference.
Please correct me where I am wrong and what knowledge I am lacking for dynamic and compile time binding or any misconception I have related to this concept.