class Student {
void cal()
{
System.out.println(this);
calculate(this);
}
void calculate(Student s)
{
System.out.println("Student");
}
void calculate(HelloWorld h)
{
System.out.println("HelloWorld");
}
}
public class HelloWorld extends Student {
public static void main(String... args) {
HelloWorld karan = new HelloWorld();
karan.cal();
}
}
OUTPUT OF CODE:
HelloWorld@65ab7765
Student
When the compiler comes across the karan.cal(), it first checks if a cal() is present in the Student class. Once confirmed and compiled, the code runs and JVM sees the object type karan is pointing to and thus executes the cal() of the Student class. When the cal() is executed, even though this contains the address for HelloWorld object, the calculate(Student s) is being run.
I know that the JVM doesn't take part in method overloading so it won't decide what calculate() to call.
Does the compiler replace this with some particular value so that even when it is pointing to a child object, the method that contains the parent reference is executed, despite there being a method that can be more suitable to point towards the child object?