Can a private method in super class be overridden in the sub-class?
Can private methods be overridden in Java? If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
Solution 1:
No, you are not overriding it. You can check by trying to mark it with @Override
, or by trying to make a call to super.func();
. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base { private void func(){ System.out.println("In base func method"); }; public void func2() { System.out.println("func2"); func(); } } class Derived extends Base { public void func(){ // Is this an overriding method? System.out.println("In Derived Class func method"); } } class InheritDemo { public static void main(String [] args) { Derived D = new Derived(); D.func2(); } }
It will print:
func2
In base func method
When you change func()
in Base
to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
Solution 2:
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func()
in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.