Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();        } } 
like image 589
AnkitChhajed Avatar asked Aug 15 '12 20:08

AnkitChhajed


People also ask

Can subclass override private methods of superclass?

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.

Can a non private method in a superclass can be overridden?

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.

Can we override private method in inner class?

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.

Why Private methods are available in subclasses if they are not accessible in subclasses?

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.


1 Answers

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 
like image 181
StandByUkraine Avatar answered Oct 13 '22 22:10

StandByUkraine