Basic Question

I am new to java and I have a basic question. I will post the code I am having problems with and ask the questions at the end.

public class Bicycle {

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

}

// the Bicycle class has four methods

public void setCadence(int newValue) {

cadence = newValue;

}

public void setGear(int newValue) {

gear = newValue;

}

public void applyBrake(int decrement) {

speed -= decrement;

}

public void speedUp(int increment) {

speed += increment;

}

}

Ok here is my problem. When you call the constructor you create an object of type Bicycle. Say the 3 number i enter into the constructor are 1,2,3. So in the constructor method it has the code

gear = startGear;

cadence = startCadence;

speed = startSpeed;

this means gear =1, cadence=2 and startgear=3

My problem is I am unsure if the gear, cadence and startgear at the start of the code is now 1,2,3 or is it only in the constructor block?

public int cadence; //does this now equal 1?

public int gear; //does this equal 2?

public int speed; //does this equal 3?

My second problem is with the 4 methods at the end of the code. I believe these are called mutator methods. Do these methods need to be called in order to run their code or do they run automatically when the constructor is called?

I hope I was clear and thanks for reading my questions.

Message was edited by:

Josiah

[1806 byte] By [Josiaha] at [2007-11-26 19:46:18]
# 1

> My problem is I am unsure if the gear, cadence and

> startgear at the start of the code is now 1,2,3 or is

> it only in the constructor block?

These three values are instance variables. They exist and retain their values throughout the lifetime of the object. That means the values are 1, 2, and 3 for any method that accesses them, It is not just in the constructor block. Likewise if you call applyBrake to change the value of speed, the changed value will exist in any and every method in the class.

>> Do these methods need to be called in order to run

> their code or do they run automatically when the

> constructor is called?

The other methods must be explicitly called in order for their code to run. You could put an explicit call in your constructor if you wanted to, although that would not make any sense in your example. Since the methods are all public, they can be called from other classes as well.

Finally, your three fields should all be declared as private, e.g.

// the Bicycle class has three fields

private int cadence;

private int gear;

private int speed;

Otherwise other classes could change those values with calling your mutator methods.

BillKriegera at 2007-7-9 22:32:03 > top of Java-index,Desktop,Developing for the Desktop...