Skip Top Navigation Bar

Superclasses

A superclass is a class that is used as the starting point for one or more other classes. A subclass inherits from the superclass by using the extends keyword. This lets you place shared data and behavior in one place instead of repeating it in every class.

A superclass is helpful when several classes have something in common.

Using superclasses make code reusable, readable, and easier to maintain. If an update to behavior needs to be made, it can be made in the superclass and the subclasses will automatically inherit this new behavior.

Student - Parent - Teacher

Consider the following UML diagrams for Student, Parent, and Teacher:

These three classes have data and behvaviors in common.

Data:

Behavior:

We can test subclass / superclass relationships using is-a. A student is-a person. A parent is-a person. A teacher is-a person.

A Person superclass can be used to represent these common data and behaviors and each subclass can then extend the superclass.

Calling the Superclass Constructor

The keyword super is used to call the constructor in the superclass from the subclass.

We use the super constructor to set the values of the data in the superclass. Here is the constructor for the Student class:

Calling the Superclass Methods

We can access the toString() method in the Person class and print the associated data for name, address, and email, we use the super keyword.

Here is the toString() method for Student:

Put it All Together

Let's try this in the Java Playground!