class Base {
private void func(){ // method overridden if public
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func(); // alternatively, this could be: ((Derived) this).func();
}
}
class Derived extends Base {
public void func(){
System.out.println("In Derived Class func method");
}
}
class Test {
public static void main(String [] args) {
Derived d = new Derived();
d.func2();
}
}
As written, this code will call the func()
of the Base class because this method is private and there is no method overriding going on.
However, if the func()
line of func2()
is changed to ((Derived) this).func()
, the func()
of the Derived class will be called.
From what I can tell, it seems as if the Derived object is being treated like a Base object once the control enters the func2()
of the Base class.
Is my understanding correct? How can my understanding be reconciled, if at all, with method overriding in the case where the func()
of the Base class is instead public
rather than private
and runtime binding occurs? Does the call to func()
in func2()
first find the Base class func()
and then decide to use func()
in the subclass due to method overriding? Exactly what happens at runtime here?