Inheritance Nuances
Consider the following code snippet
Student john = new Student("John Doe", "john@email.com");
GradStudent jane = new GradStudent("Jane Doe", "jane@email.com");
System.out.println(jane.getName() + " and " + john.getName());
Exercise What is printed out?
(a) Jane Doe and John Doe 
(b) Jane Doe and Jane Doe 
(c) null and John Doe 
(d) and John Doe 
Solution
The correct answer is (a). Note that:
- The private fields/methods are inherited; so janeindeed has anamefield with the value "Jane Doe".
- johnand- janeare two separate objects - the use of- superkeyword to invoke the constructor of- Studentin- GradStudent's constructor does not link the objects of these two classes to one another.
Consider adding the following method to the GradStudent class which raises the compilation error "name has private access in Student".
public String toString() {
    return name + " " + email;
}
Exercise How can we resolve the compilation error? (There may be more than one correct answer!)
(a) you need to use super.name and super.email instead 
(b) you need to use super(name) and super(email) instead 
(c) private fields/methods are not inherited so you cannot access them 
(d) you need to use getName() and getEmail() instead  
(e) you must change the visibility of name and email from private to protected or public in Student class
Solution
The correct answers are (d) and (e) with a preference of doing (d) over (e).
Are private fields/methods inherited? Yes! A subclass inherits everything from its superclass. However, the inherited fields (or methods) that are declared private in a superclass are not directly accessible in subclasses.
If it is important to directly access a private property of the superclass, then it must be declared with a visibility modifier of protected (visible to subclasses but hidden from the outside world!). Be sparing in the use of protected visibility, especially for fields; in most cases you don't need direct access to them and you are better off using getters/setter to access them.
Resources
- Baeldung has a great article on Java Access Modifiers.
- Oracles Java Tutorials on Controlling Access to Members of a Class
- This discussion on StackOverflow is interesting.