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 a note of the following:
-
To inherit from a class, use the
extends
keyword as inGradStudent extends Student { ... }
. -
The sub-class must not redefine the fields/methods of the super-class (unless for overriding, which will be discussed later).
-
The constructors of a super-class, unlike fields and methods, are not inherited by a sub-class. You must define non-default constructors of a sub-class. The constructors of the sub-class can invoke the constructors of the super-class 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. Therefore, it can be used to access fields and methods of the parent class.Call to
super()
must be the first statement in the sub-class 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.