Private members in Java inheritance
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?
This kind of depends on your exact usage of the word inheritance. I'll explain by example.
Suppose you have two classes: Parent
and Child
, where Child
extends Parent
. Also, Parent
has a private integer named value
.
Now comes the question: does Child
inherit the private value
? In Java, inheritance is defined in such a way that the answer would be "No". However, in general OOP lingo, there is a slight ambiguity.
You could say that it not inherited, because nowhere can Child
refer explicitly to value
. I.e. any code like this.value
can't be used within Child
, nor can obj.value
be used from some calling code (obviously).
However, in another sense, you could say that value
is inherited. If you consider that every instance of Child
is also an instance of Parent
, then that object must contain value
as defined in Parent
. Even if the Child
class knows nothing about it, a private member named value
still exists within each and every instance of Child
. So in this sense, you could say that value
is inherited in Child
.
So without using the word "inheritance", just remember that child classes don't know about private members defined within parent classes. But also remember that those private members still exist within instances of the child class.