Let's assume that your class, MountainBike inherits from Bike. The word super is a reference to a class's parent class.
If Bike has a constructor which looks like this:
public Bike(int startCadence, int startSpeed, int startGear) {
cadence = startCadence;
speed = startSpeed;
gear = startGear;
}
Then the MountainBike constructor which looks like this:
public MountainBike(int startCadence, int startSpeed, int startGear, int startHeight) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
is almost equivalent to this:
public MountainBike(int startCadence, int startSpeed, int startGear, int startHeight) {
super.cadence = startCadence;
super.speed = startSpeed;
super.gear = startGear;
seatHeight = startHeight;
}
Except the former, where we call the super constructor is better. For one, it avoids duplicating code. For two, it saves two lines. For three, if I need to include some verification logic on speed for example, I can just include it in the Bike constructor and don't need to duplicate that code in the MountainBike constructor as well.
chepner's answer explains some other reasons why the second version can be problematic. But this answer hopefully helps explain what the call to the super constructor is doing.
No comments:
Post a Comment