Saurab Parakh Saurab Parakh - 2 months ago 10
Java Question

How can a derived class invoke private method of base class?

public class PrivateOverride {

private void f() {
System.out.println("private f()");

public class Derived extends PrivateOverride {

public void f() { //this method is never run.
System.out.println("public f()");

public static void main(String[] args) {

// instantiate Derived and assign it to
// object po of type PrivateOverride.
PrivateOverride po = new Derived();

// invoke method f of object po. It
// chooses to run the private method of PrivateOveride
// instead of Derived

So, the output of this code is
private f()
. Now, the question arises to my mind: how can po which is an object of Derived Class call a private method of PrivateOverride which is its base class?


Because you defined the main method in PrivateOverride class. If you put the main method in Derived class, it would not compile, because .f() would not be visible there.

po.f() call in PrivateOverride class is not a polymorphism, because the f() in PrivateOverride class is private, so f() in Derived class is not overriden.