Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private members in Java inheritance

I was told that for a Java subclass it can inherit all members of its superclass. So does this mean even private members? I know it can inherit protected members.

Can someone explain this to me. I am now totally confused.

like image 959
Mandy M Avatar asked Jul 01 '11 03:07

Mandy M


People also ask

Can inheritance access private members?

With private inheritance, public and protected member of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object. However, they can be used inside the member functions of the derived class.

How can you make the private members inheritable in Java?

The private members of the superclass remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the members of the subclass. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.

How can we inherit the private members of a class?

Private members are accessible only within the class in which they are declared. So even if you inherit the class, you will have access only to the public and protected members of the base class but private members are not inherited(accessible).


1 Answers

No, the private member are not inherited because the scope of a private member is only limited to the class in which it is defined. Only the public and protected member are inherited.

From the Java Documentation,

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

From the JLS,

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

A useful link : Does subclasses inherit private fields?

like image 134
Saurabh Gokhale Avatar answered Sep 21 '22 20:09

Saurabh Gokhale