Do Subclasses Inherit Private Instance Variables From Superclasses

Ian picture Ian · May 8, 2012 · Viewed 31.6k times · Source

Do subclasses inherit private fields?

This question addresses the same problem but I don't quite understand how that satisfies the (seemingly) contradictory situations below.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Says that "A subclass does not inherit the private members of its parent class."

This means that it neither inherits private instance variables nor private methods right?

However, how does this work if it inherits a public accessor method from its parent? It returns an instance variable that it doesn't know exists?

Also, my computer science book (Baron's AP Computer Science A) has the correct answer to a question that says that "The (Subclass) inherits all the private instance variables and public accessor methods from the (Superclass)."

Isn't this in contraction to oracle's tutorial?

Thanks for your help

Answer

QuantumMechanic picture QuantumMechanic · May 8, 2012

The accessor will work fine. Remember that the accessor runs in the "context" of the superclass and so the accessor will be able to see the member that's hidden from the subclasses.

As for the textbook, it depends on your point of view. The subclass inherits the private members in the sense that they are actually there inside instances of the subclass (so they'll take up memory, etc.), but the subclass will be unable to directly access them.