1.

Can we override private methods in Java?

Answer»

No, PRIVATE methods cannot be overridden in JAVA. The private keyword limits the scope of the method, variable or class with which it is declared.

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

Let us see what happens when we TRY to override a private method:

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();  }   }

The output is as follows:

$javac Example.java 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.



Discussion

No Comment Found