Inheritance syntax in Java
Here is the GradStudent
class again:
public class GradStudent extends Student {
private String advisor;
public GradStudent(String name, String email) {
super(name, email);
}
public void setAdvisor(String advisor) {
this.advisor = advisor;
}
public String getAdvisor() {
return advisor;
}
}
Make note of the following:
-
To inherit from a class, use the
extends
keyword as inGradStudent extends Student { ... }
. -
The subclass must not redefine the fields/methods of the superclass (unless for overriding which will be discussed later).
-
Unlike fields and methods, the constructors of a superclass are not inherited by a subclass. You must define non-default constructors of a subclass. The constructors of the subclass can invoke the constructors of the superclass using the
super
keyword.public GradStudent(String name, String email) { super(name, email); }
The keyword
super
is similar to thethis
keyword but it points to the parent class. It can be used to access fields and methods of the parent class.Call to
super()
must be the first statement in the subclass constructor.We could update (or overload) the constructor of
GradStudent
to take an initial value for advisor:public GradStudent(String name, String email, String advisor) { super(name, email); this.advisor = advisor; }
Resources
- Oracle's Java Tutorial Providing Constructors for Your Classes - read on default vs. non-default constructors.
- Oracle's Java Tutorial Using the Keyword super.
- Oracle's Java Tutorial Hiding Fields.