Can We Override Private Method in Java?

No, we cannot override private methods because the scope of private methods is limited to the class and we cannot access them outside of the class which they are define in.

Just like static and final methods, private methods in Java use static binding that is done at compile time. That's the reason we will get compile time error, when we try to override private methods.

class Base { 
  private void fun() { 
     System.out.println("Base fun");      
  } 
} 
 
class Derived extends Base { 
  private void fun() { 
     System.out.println("Derived fun");   
  } 
  public static void main(String[] args) { 
      Base obj = new Derived(); 
      obj.fun(); 
  }   
}

We get compile time error: fun() has private access in Base. It is because compiler tries to call base class function that is declared private, hence cannot be overridden.

Inner class is saviour: An Inner classes can access private members of its outer class, for example in the following program, fun() of Inner accesses private data member msg which is fine by the compiler.

/* Java program to demonstrate whether we can override private method  
   of outer class inside its inner class */
class Outer { 
     private String msg = "GeeksforGeeks"; 
     private void fun() { 
          System.out.println("Outer fun()"); 
     } 
 
     class Inner extends Outer { 
         private void fun()  { 
               System.out.println("Accessing Private Member of Outer: " + msg); 
         } 
     } 
 
     public static void main(String args[])  { 
 
          // In order to create instance of Inner class, we need an Outer  
          // class instance. So, first create Outer class instance and then 
          // inner class instance. 
          Outer o = new Outer(); 
          Inner  i   = o.new Inner(); 
 
          // This will call Inner's fun, the purpose of this call is to  
          // show that private members of Outer can be accessed in Inner. 
          i.fun();   
 
          // o.fun() calls Outer's fun (No run-time polymorphism). 
          o = i;  
          o.fun(); 
     } 
}
 
Output:
=======
Accessing Private Member of Outer: GeeksforGeeks
Outer fun()
 

Hope you have enjoyed reading this post. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.