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(); } }
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.
Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.
1) In Java, inner Class is allowed to access private data members of outer class. This behavior is same as C++ (See this). 2) In Java, methods declared as private can never be overridden, they are in-fact bounded during compile time.
Private methods are inherited in sub class ,which means private methods are available in child class but they are not accessible from child class,because here we have to remember the concept of availability and accessibility.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With