Can we override a private or static method in Java

Java 8Object Oriented ProgrammingProgramming

No, we cannot override private or static methods in Java.

Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.

Example

Let us see what happens when we try to override a private method −

 Live Demo

class Parent {
   private void display() {
      System.out.println("Super class");    
   }
}
public class Example extends Parent {
   void display() // trying to override display() {
      System.out.println("Sub class");
   }
   public static void main(String[] args) {
      Parent obj = new Example();
      obj.display();
   }
}

Output

The output is as follows −

Example.java:17: error: display() has private access in Parent
obj.method();
      ^
1 error

The program gives a compile time error showing that display() has private access in Parent class and hence cannot be overridden in the subclass Example.

If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.

Example

Let us see what happens when we try to override a static method in a subclass

 Live Demo

class Parent {
   static void display() {
      System.out.println("Super class");    
   }
}
public class Example extends Parent {
   void display() // trying to override display() {
      System.out.println("Sub class");
   }
   public static void main(String[] args) {
      Parent obj = new Example();
      obj.display();
   }
}

Output

This generates a compile-time error. The output is as follows −

Example.java:10: error: display() in Example cannot override display() in Parent
void display() // trying to override display()
    ^
overridden method is static
1 error
raja
Published on 03-Jan-2019 14:58:15
Advertisements