Code reuse through Inheritance

  • Define inheritance.
  • Detect inheritance in Java class declaration.

Here is the GradStudent class declared as a sub-class of Student:

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;
  }
}

The declaration of GradStudent contains what was specific to it; all the shared attributes and operations are now inherited from the Student class.

Inheritance is a mechanism that allows classes to be derived from other classes, with the child classes inheriting fields and methods from the parent classes.

Another name for "child class" is sub-class or derived class. The "parent class" is also called the super-class or base class.

In addition to the properties inherited from the super-class, the sub-class can define its fields and methods.

Note that in the example of the GradStudent and Student classes, the Student class is the parent class, while the GradStudent class is the child class since it inherits properties from the super-class and defines fields and methods of its own.

Inheritance is a one-way relationship! Therefore, the parent class does not have access to the (additional) attributes/methods declared in a child class.

Resources