Answers

Question and Answer:

  Home  Java Software Engineer

⟩ How to override a private or static method in Java?

You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.

class Base {

private static void display() {

System.out.println("Static or class method from Base");

}

public void print() {

System.out.println("Non-static or instance method from Base");

}

class Derived extends Base {

private static void display() {

System.out.println("Static or class method from Derived");

}

public void print() {

System.out.println("Non-static or instance method from Derived");

}

public class test {

public static void main(String args[])

{

Base obj= new Derived();

obj1.display();

obj1.print();

}

}

 129 views

More Questions for you: