JavaTip: Can we override private method in Java

No, We can not override private method in Java, just like we can not override static method in Java. Like static methods, private method in Java is also bonded during compile time using static binding by Type information and doesn’t depends on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, its not possible to override private method in Java. private methods are not even visible to Child class, they are only visible and accessible in the class on which they are declared. private keyword provides highest level of Encapsulation in Java. Though you can hide private method in Java by declaring another private method with same name and different method signature.

Overriding private method in Java – Testing

As per above paragraph we can not override private method in Java because its bonded during compile time using static binding. Now let’s test this theory by an example Java program :

/**** Java program to demonstrate that private method can not be overridden in Java.* This Java programs calls both private and non private method with child class* object on constructor of parent class.* Only non private method of Child class invoked while private method of* Parent class is invoked, Which confirms that private method can not be overridden in Java* and only be hidden if we declare same message in Child class.* @author*/publicclass PrivateMethodCanNotBeOverriden{publicstaticvoid main(String args[]) {//shows that private method can not be overridden in Java Parent parent = new Child();}}class Parent{public Parent(){ name(); normal();}privatevoid name(){System.out.printf(“private method inside Parent class in Java %n”);}publicvoid normal(){System.out.println(“non private method from Parent class can be overridden”);}}class Child extends Parent{/* * Private method can not be overridden in Java, they can only be hidden */privatevoid name(){System.out.printf(“private method inside Child class in Java %n”);} @Overridepublicvoid normal(){System.out.println(“non private overridden method from Child class “);}}Outputprivate method inside Parent class in Javanon private overridden method from Child class