Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do subclasses inherit private fields?

This is an interview question.

Does subclasses inherit private fields?

I answered "No", because we can't access them using the "normal OOP way". But the interviewer thinks that they are inherited, because we can access such fields indirectly or using reflection and they still exist in the object.

After I came back, I found the following quote in the javadoc:

Private Members in a Superclass

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

Do you know any arguments for the interviewer's opinion?

like image 979
Stan Kurilin Avatar asked Oct 07 '22 10:10

Stan Kurilin


People also ask

Do subclasses inherit instance variables?

Subclasses do not have access to the private instance variables in a superclass that they extend. Constructors are not inherited.

Do subclasses inherit public methods?

All public and protected methods and variables will be inherited. Any methods with the same signature in the subclass will override the superclass behavior. The subclass will not inherit private methods and variables.

Does a class inherit private methods?

private methods are not inherited. A does not have a public say() method therefore this program should not compile.


1 Answers

Most of the confusion in the question/answers here surrounds the definition of Inheritance.

Obviously, as @DigitalRoss explains an OBJECT of a subclass must contain its superclass's private fields. As he states, having no access to a private member doesn't mean its not there.

However. This is different than the notion of inheritance for a class. As is the case in the java world, where there is a question of semantics the arbiter is the Java Language Specification (currently 3rd edition).

As the JLS states (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):

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.

This addresses the exact question posed by the interviewer: "do subCLASSES inherit private fields". (emphasis added by me)

The answer is No. They do not. OBJECTS of subclasses contain private fields of their superclasses. The subclass itself has NO NOTION of private fields of its superclass.

Is it semantics of a pedantic nature? Yes. Is it a useful interview question? Probably not. But the JLS establishes the definition for the Java world, and it does so (in this case) unambiguously.

EDITED (removed a parallel quote from Bjarne Stroustrup which due to the differences between java and c++ probably only add to the confusion. I'll let my answer rest on the JLS :)

like image 260
robert_x44 Avatar answered Oct 19 '22 00:10

robert_x44