views:

65

answers:

3

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?

+2  A: 

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.

mvid
the whole example can be found here:http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html
elementz
This tutorial is a Constructors tutorial. I bet they assume that the instance variables already exist. Good luck!
mvid
+2  A: 

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.

Jon Skeet
A: 

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

Winter