<< Hide Menu
2 min read•june 18, 2024
Avanish Gupta
Milo Chang
Avanish Gupta
Milo Chang
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!
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.
We will use super in the following scenario. We have a Quadrilateral superclass with a constructor, an area() method, and an isEquivalent() method. We have the method headers written in the quadrilateral class, but we won't show the implementation.
/** Represents a quadrilateral
*/
public class Quadrilateral {
double sideOne;
double sideTwo;
double sideThree;
double sideFour;
/** Makes a quadrilateral with 4 sides of length sideOne, sideTwo, sideThree, sideFour
*/
public Quadrilateral(double sideOne, double sideTwo, double sideThree, double sideFour) {
}
/** Calculates the area of the quadrilateral
*/
public double area() {
}
/** Determines whether another quadrilateral with given side lengths is the same as the object we have
*/
public boolean isEquivalent(double sideOne, double sideTwo, double sideThree, double sideFour) {
}
}
Now, we want to make a subclass that represents a Rectangle. First, we will have to make the method header and constructor of the Rectangle class:
/** Represents a rectangle
*/
public class Rectangle extends Quadrilateral {
/** Makes a rectangle given a length and width
*/
public Rectangle(double length, double width) {
super(length, width, length, width);
}
}
By calling the super constructor here, we are using the Quadrilateral constructor but using the parameters passed into the Rectangle constructor as the Quadrilateral constructor parameters. If the Rectangle class has any extra instance variables not in the Quadrilateral class, they would be initialized separately.
If Quadrilateral was a subclass of another class, say the Shape class, the constructor for Quadrilateral could use super to call the constructor for the Shape class. The process of calling superclass constructors continues until the Object constructor is called, regardless of whether the superclass constructor is called implicitly or explicitly. The Object class is the ultimate superclass of all classes in Java. At this point, all of the constructors within the hierarchy would execute, starting with the Object constructor.
© 2024 Fiveable Inc. All rights reserved.