![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we override private methods in Java
Ideally No. But, using the tricky code, a subclass can override a private method as well. See the example below −
Example
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.
Advertisements