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

Can private method be overriden in Java 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
*/
public class PrivateMethodCanNotBeOverriden{
public static void main(String args[]) {
//shows that private method can not be overridden in Java    
        Parent parent = new Child();
}
}
class Parent{
public Parent(){
        name();
        normal();
}
private void name(){
System.out.printf(“private method inside Parent class in Java %n”);
}
public void 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
     */

private void name(){
System.out.printf(“private method inside Child class in Java %n”);
}
    @Override
public void normal(){
System.out.println(“non private overridden method from Child class “);
}
}
Output
private method inside Parent class in Java
non private overridden method from Child class

One thought on “JavaTip: Can we override private method in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s