Home » Core Java » Can we override private,static and final method in Java

Can we override private,static and final method in Java

Can we override private,static and final method in Java ?” This is a very tricky question in the java interview room.Interviewer can ask you any of these also like “Can we override private method in Java  ?” or “Can we override static  method in Java ?” or “Can we override final method in Java ?“.I thought of explaining all these in the same page so that your time will be saved and you can understand,compare and remember this question for long time.I will divide the question and explain in further below.

Can we override private method in Java  ?

The answer is no.
1. Private method of one class is not visible in another class.We can never call private method of any class in another class directly.This rule is applicable for classes having parent-child relation as well.
2. You can only hide private method of super class in sub class.

In Program 1, we have created printPrivate() method in both Parent class and Child class.We have called these private methods in the constructor of both the classes.After this when we try to create object of Child class ,first constructor of parent then constructor of child is called and output is printed.If we comment out printPrivate() in the constructor of Parent class ,then we are hiding the printPrivate() of Parent class.Output of Program2 shows method hiding.
Program 1::

Output::

Program 2::

Output::


Leave a comment

Your email address will not be published. Required fields are marked *

nineteen + 19 =