Exploring the super keyword
The super
keyword is used in a subclass in two specific scenarios: to call a parent constructor and to access parent members (typically methods). When an object is constructed, the order of constructor calls is very important. Bearing in mind that we now have the possibility of having many classes in an inheritance hierarchy, the order of constructor calls is from the top down. This means that, the parent constructor is always called before the subclass constructor. If you have a hierarchy where Toyota
“is-a” Car
and Car
“is-a” Vehicle
, then when you go to create a Toyota
object, the order of constructor calls is as follows: Vehicle
is first, Car
is second, and Toyota
is last.
There is a good reason for this. Firstly, remember that the constructor’s role is to initialize the instance members of the class. Now, given that the subclass constructor may use inherited members from its parent when initializing its own members...