Why does it work like this? (A constructor question)

Hi there, I’m pretty new to Java and I was wondering about the following.

Why is it that we in the method signature we use different names (like int startCadence in the example below) when afterwards we still keep using the names of the instance fields in the methods (like cadence, in the example below)?

Why is it not for example (compare to public class Bicycle example below):

public Bicycle(int cadence, int gear, int speed) {
//why is something here still needed? why do we need this seemingly extra reference? 
}

I can see how it works, but don’t understand why it works like this. Can anyone help me? I must be stating the obvious here, but unfortunately this has been puzzling me.

(example below from The Java Tutorial)

public class Bicycle {
        
    // the Bicycle class has
    // three fields
    public int cadence;
    public int gear;
    public int speed;
        
    // the Bicycle class has
    // one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
        
    // the Bicycle class has
    // four methods
    public void setCadence(int newValue) {
        cadence = newValue;
}

I think the idea here is that these are variables that may change and this is just descriptive naming (or the classic name matches intent). Part of your constructor’s job is to initialise these values naming the inputs like startGear or startingGear would make sense. As attributes of the object they may be expected to change so a less specific gear might be more appropriate.

1 Like

Thank you for explaining! @tgrtim

1 Like