zuai-logo

Writing Constructors for Subclasses

Emily Wilson

Emily Wilson

4 min read

Listen to this study note

Study Guide Overview

This study guide covers subclass constructors and the super keyword in Java. It explains how to use super to call superclass constructors, including default constructors. An example demonstrates creating a Rectangle subclass from a Quadrilateral superclass, illustrating constructor inheritance and initialization.

While methods and instance variables of a superclass are carried over to a subclass, constructors are not. That means that we have to write our constructors again!

The Super Keyword

Luckily, we don't have to start over from scratch. We have a special keyword that can help us. This is the super keyword. We will learn how to use it with constructors in this topic and then with methods in the next topic.

Using the super keyword, we can call the superclass’s constructor and use that to construct an object of the subclass.

If a subclass’s constructor doesn't explicitly call a superclass’s constructor using super, Java will insert a call to the superclass’s no-argument constructor.

##...

Question 1 of 7

When a subclass is created, what happens to the constructors of its superclass? 🤔

They are automatically inherited

They are automatically overridden

They are not inherited and must be defined in the subclass

They are automatically overloaded