Consider the below two classes

public class Parent {
  private void privateMethod() {
    System.out.println("private method of parent");
  }

  public void publicMethod() {
    this.privateMethod();
  }
}

public class Child extends Parent {
  private void privateMethod() {
    System.out.println("private method of child");
  }

  public void publicMethod() {
    super.publicMethod();
  }
}

What will be the out put of below?

  public static void main(String[] args) {
    Child child = new Child();
    child.publicMethod();
  }

The above prints “private method of parent”.

Now let us make the private method public in both parent and child and run the code again as below.

public class Parent {
  public void privateMethod() {
    System.out.println("private method of parent");
  }

  public void publicMethod() {
    this.privateMethod();
  }
}

public class Child extends Parent {
  public void privateMethod() {
    System.out.println("private method of child");
  }

  public void publicMethod() {
    super.publicMethod();
  }
}


  public static void main(String[] args) {
    Child child = new Child();
    child.publicMethod();
  }

The above prints “private method of child”.

I thought about this for sometime as to why when the method is private, parent class private method is chosen and the best reason I could think of is, JVM statically binds private methods into the class code while the public methods are dynamically resolved at runtime to enable runtime polymorphism.

Advertisements