Java Constructors

The constructors can appear anywhere in the code for the class. However, by convention, most people put them before any other functions that aren’t constructors.

As for the variable names, all 6 are actually variable names, but the scope is differnet. The ones specified as parameters to the constructor (startCadence, startSpeed, startGear) are only available within the constructor. The other 3 (gear, cadence, speed) are probably class-wide variables, available to all methods. However the definition isn’t shown in your code snippet. The full class would look mroe like:

class Bicycle
{
    // class-level variables
    private int gear;
    private int cadence;
    private int speed;

    // constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    // another method (not a constructor)
    public void ShiftUp() {
        gear = gear + 1; // notice the 'gear' variable is available here too.
    }
}

Hope that helps!

Leave a Comment