Which method is called during Constructor chain execution with an overriding method? Given the following two classes I need to know which setGear method would be called when creating a MountainBike object. My real project has nothing to do with bicycles, I am trying to override a class to change the behavior of one method that is called in the constructor of the super class and I’m not sure how it should work…
public class Bicycle {
public int cadence;
public int gear;
public int speed;
public Bicycle(int startCadence,
int startSpeed,
int startGear) {
setGear(startGear);
setCadence(startCadence);
setSpeed(startSpeed);
}
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
public class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
public void setHeight(int newValue) {
seatHeight = newValue;
}
public void setGear(int newValue) {
if(newValue<4)
gear = newValue;
else{
gear = 4;
}
}
}
If you instantiate the overriding class, then its overriding methods will be the ones executed.
— Edit: to reflect OP edited question (
setGearis now called from withinBicycle‘s constructor) —Given that you instantiate a
MountainBike,MountainBike‘ssetGeargets executed.