Can we override private methods in Java

Java8Java Programming Object Oriented Programming

Ideally No. But, using the tricky code, a subclass can override a private method as well. See the example below −

Example

Live Demo

class A {
   private void display() {
      System.out.println("A.display");
   }
    public void callDisplay() {
      System.out.println("A.callDisplay");
      display();
   }
}

class B extends A {
   private void display() {
      System.out.println("B.display");
   }
    public void callDisplay() {
      System.out.println("B.callDisplay");
      display();
   }  
}

public class Tester {
   public static void main(String[] args) {
      A a = new B();
      a.callDisplay();

      B b = new B();
      b.callDisplay();

      A a1 = new A();
      a1.callDisplay();
   }
}

Output

B.callDisplay
B.display
B.callDisplay
B.display
A.callDisplay
A.display

In above example, an object is of B class, the a.callDisplay() makes a call to callDisplay() method of B which in turn calls B's display method.

As per the Java's documentation The Java Tutorials: Predefined Annotation Types.

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

Add @Override annotation over B.display() method. Java compiler will throw the error.

class B extends A {
   @Override
   private void display() {
      System.out.println("B.display");
   }

   public void callDisplay() {
      System.out.println("B.callDisplay");
      display();
   }  
}

Output

The method display() of type B must override or implement a supertype method.
raja
Published on 20-Jul-2018 16:54:11
Advertisements