- 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 a private or static method in Java
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 −
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
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