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?
a source to share
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
.
a source to share
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.
a source to share