Defining the type of variables / fields inside a constructor, how is this done?

I just looked through the Suns Java tutorial and found something that completely confused me: In the following example:

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

      

}

Why is it that the types of variables (fields?), Speed ​​and speed do not need to be defined? I would write it like this:

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

      

}

What is the actual difference?

+2


a source to share


3 answers


Your code will declare local variables - they will be effectively removed when the constructor has finished. Let's take a look at some more contextual code :

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

      



Now you can see the declarations - they are declared outside of the constructor because they are instance fields instead of local variables. They compose data for each instance of the class Bicycle

.

+2


a source


These fields were probably already defined earlier in the class before the constructor. Can we see the whole class?



Constructors are just one part of a class and usually do not contain instance variable initialization. You will usually see the ones defined at the top of the class.

+2


a source


They have been defined as class variables and are implicitly nested. For greater clarity, he could read

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

0


a source







All Articles