Can You Override Private Method in Java ? Example

No, We can not override the private method in Java, just like we can not override the static method in Java. Like static methods, the private method in Java is also bonded during compile time using static binding by Type information and doesn't depend on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, it's not possible to override the private method in Java. 

private methods are not even visible to the Child class, they are only visible and accessible in the class on which they are declared. private keyword provides the highest level of Encapsulation in Java.

Though you can hide the private method in Java by declaring another private method with the same name and different method signature.



Overriding a private method in Java? Example

As per the above paragraph, you can not override the private method in Java because it's bonded during compile time using static binding. It's also not visible on sub-class so cannot be overridden but you can hide the method by declaring another private method of the same signature. 

You can also see these free Java courses to learn more about such Java Fundamentals. 

Can You Override Private Method in Java ? Example


 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 program calls both private and non-private methods with child class
 * object on the constructor of the parent class.
 * Only non-private method of Child class invoked while the private method of
 * Parent class is invoked, Which confirms that the private method can not be overridden in Java
 *  and only be hidden if we declare the 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 methods 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
the private method inside Parent class in Java
the non-private overridden method from Child class


This example has two classes Parent and Child each contains two methods with the same name and same signature, one of them is a private method and the other is non-private, public in this case. 

On constructor of Parent class, we call both private and non-private method and Output shows that overriding only applies in case of non-private method.

By the way, calling an overridden method from a constructor is considering as bad practice and I have just shown here to demonstrate that we can not override the private method in Java.



Other Java OOP tutorials you may like

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about learning object-oriented programming and looking for a free online course to start with then you can also check this FREE Object Oriented Programming (OOPs) for JAVA Interviews course on Udemy. It's completely free and you just need a free Udemy account to join this course. 

Now, its quiz time so one question for? Can we override a static method in Java? Can you explain with a reason?

15 comments:

  1. Good points :
    Private method is not inherited by subclass in Java. Sub class can not even see private methods of super class. when you declare private method in subclass no body knows about it except code in that class. That's why term method hiding is used. Accessing private method outside class is compile time error in Java.

    ReplyDelete
    Replies
    1. That's true.. It adds some more information to this article.. :)

      Delete
  2. Good this article is very useful for me

    ReplyDelete
  3. Useful information.
    Thanks!

    ReplyDelete
  4. Can we override a private method from super class into subclass? is that different than creating private method with same name in both super class and sub class in Java?

    ReplyDelete
    Replies
    1. Yes sir you are right. It is 2 different things declaring same method with private in super and sub class.. . And overriding is super class method to sub. Supper class method is private and we can't override it. .. .

      Delete
  5. Good Article, asked in two interviews consecutively.

    ReplyDelete
  6. "Can we override a private method from super class into subclass? is that different than creating private method with same name in both super class and sub class in Java?"
    -> Thats a compile time error. compiler wont find anything to override since it cant see the private method

    ReplyDelete
    Replies
    1. @mugume, I don't think that's true. You can see in my example, I have same method name() in both super class and sub class. It's actually an example of method hiding than overloading. If a method is marked private, compiler won't bother to check super class.

      Delete
    2. that error will only occur it you use
      @Override annotation

      Delete
  7. Hello In this Program you are not getting any compile time error if you want you can check.@mugume david

    public class Prgoram2 {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Derived d=new Derived();


    }

    }
    class BaseClass
    {
    private void m1()
    {

    }
    }
    class Derived extends BaseClass
    {
    private void m1()
    {

    }
    }

    ReplyDelete
  8. You have cretaed object only in above program....didn't invoke any method.

    ReplyDelete
    Replies
    1. @Sujit, since methods are invoked from constructor, they will automatically be called when you create an object of the class. You don't need to invoke any method.

      Delete
  9. Another thing that can be noted is that private method can't be overriden even if it's visible - for example in an Inner or Nested class. This example code will give a compilation error even though the private method from the base class is visible inside the inner child class:

    class BaseClass {
    private void method() {
    System.out.println("In parent");
    }

    class ChildClass extends BaseClass {
    @Override
    private void method() {
    System.out.println("In child");
    }
    }
    }

    It will give: "The method method() of type BaseClass.ChildClass must override or implement a supertype method"

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.