Definition of variables/fields type within a constructor, how is it done?
I just had a look at Suns Java tutorial, and found something that totally confused me: Given the following example:
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
Why is it, that the types of the variables (fields?) gear, cadence and speed do not need to be defined? I would have written it as follows:
public Bicycle(int startCadence, int startSpeed, int startGear) {
int gear = startGear;
int cadence = startCadence;
int speed =开发者_如何学运维 startSpeed;
}
What would be the actual differnce?
Your code would declare local variables - they'd be effectively gone when the constructor finished. Let's have a look at the code with more context:
// 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're declared outside the constructor because they are instance fields instead of local variables. They make up the data for each instance of the Bicycle
class.
It is likely that those fields were already defined earlier in the class, before the constructor. Can we see the whole class?
Constructors are just one part of a class, and do not generally contain the initiation of instance variables. You will generally see those defined at the top of the class.
They were defined as class variables and are getting an implicit this attached. For better clarity it could read
public Bicycle(int startCadence, int startSpeed, int startGear) { this.gear = startGear; this.cadence = startCadence; this.speed = startSpeed; }
精彩评论