Search code examples
javamethodsconstructorchainoverriding

Which method is called during Constructor chain execution with an overriding method


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;
        }

    }    
}

Solution

  • If you instantiate the overriding class, then its overriding methods will be the ones executed.

    Bicycle bike;
    
    bike = new Bicycle(1,2,3);
    bike.setGear(8);//Bicycle's setGear is run
    
    bike = new MountainBike(1,2,3,4);
    bike.setGear(8);//MountainBike's setGear is run
    

    -- Edit: to reflect OP edited question (setGear is now called from within Bicycle's constructor) --

    Bicycle b=new MountainBike(1,2,3,4);
    

    Given that you instantiate a MountainBike, MountainBike's setGear gets executed.