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:
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
Bicycleclass.