Method overriding and Private Methods

We know that, we can override a public or protected method of parent class in the child class as long as we obey the method overriding principles.
 
But how about private methods ?
 

Can we override a private method of a class in the child class ?

 
 

In the following program, we have a private method hello() in both the parent and child class with same signature.
 

But, there is no compilation failure. This program runs fine and produces the following output :

 

Hello ClassB
 
 
Here is the program code:
 

package com.javatutorial;

public class ClassA {

  private void hello(){
    System.out.println("hello");
  }
}

package com.javatutorial;

public class ClassB extends ClassA {

  public static void main(String[] args) {

    new ClassB().hello();
  }

  private void hello(){
    System.out.println("Hello ClassB");
  }
}


 
 

In Java, it is not possible to override a private method of base class in the child class. This is because, the private method is not visible in the Child class.

 
However, Java allows us to add a new method in the child class with the same or modified signature. So, we can have a child class with hello() method with same signature.

 
 

So, how is it different from method overriding ??

 

The difference is, we are adding a new method in child class here that is unrelated to the parent class version.
 

This is not method overriding, rather we can call it method redeclaration. So, none of the rules of method overriding apply here.

 
If the parent class method was public/protected, Class B will fail to compile because the method overriding rules will fail.

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

2 comments

  1. Then if you try the following:

    ClassA clazz = new ClassB();
    clazz.hello();

    it will print hello method from ClazzA

  2. […] Method Overriding and Private methods […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: