educative.io

The Vehicle constructor calls super()

Why does the Vehicle class constructor need to call super()? What is the parent class to the Vehicle class?

Thanks.


Course: https://www.educative.io/collection/6650775272947712/6368023997317120
Lesson: https://www.educative.io/collection/page/6650775272947712/6368023997317120/6721407262654464

Hi @Nathan_Lin !!
In Java, when a class extends another class (i.e., it is a subclass or child class), the subclass constructor needs to invoke the constructor of the superclass (i.e., the parent class) using the super() keyword. This is done to ensure that the initialization code defined in the parent class is executed before the subclass-specific initialization code.

In the given code, the Vehicle class implements the Comparable<Vehicle> interface, indicating that it can be compared to other Vehicle objects. Since Vehicle is not explicitly declared as a subclass of any other class (using the extends keyword), it is implicitly a subclass of the Object class, which is the root class for all Java classes.

By calling super() in the constructor of the Vehicle class, it invokes the default constructor of the Object class. The Object class constructor initializes any necessary internal state of the object. In this case, it is not strictly required to call super() explicitly because the Java compiler automatically inserts it if no superclass constructor is called explicitly.

In summary, the super() call in the constructor of the Vehicle class is necessary to invoke the constructor of its superclass (Object class).
I hope it helps. Happy Learning :blush:

2 Likes