A (175)

(Tuis.) #1

140 CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces


A common reason to use a method without any parameters is to invoke a state change in an object
that does not depend on any data being passed in. In the case of this particular gear shifting example,
this would also fix a potential problem of skipped gears, as you would simply code a .shiftGearUp()
method and a .shiftGearDown() method, which would upshift and downshift by one gear level
each time they were called, rather than change to a gear selected by the driver. If you have ever
shifted from first into fifth gear on your car, you know that it does not work very well, and can cause
a stall. This might be a smarter way to code this particular method, and then you would not need
to pass a parameter in order to shift gears on your Car object; you would just call .shiftGearUp( ) or
.shiftGearDown( ) whenever any gear shifting for the Car object was needed.


After the method declaration, the method’s programming logic procedures are contained inside
the curly braces. In this Car class and object definition example, we have four methods as defined
back in Figure 5-1:


   The .shiftGears( ) method will set the Car object’s gear to the gear value that
was passed into the .shiftGears() method. You should allow an integer to be
passed into this method, to allow “user error,” just as you would when you are
driving your car in the real world.

void shiftGears (int newGear) {
gear = newGear;
}

   The .accelerateSpeed( ) method takes your object’s speed state variable and
then adds your acceleration factor to the speed, which causes your object
to accelerate. This is done by taking your object’s current speed setting, or
state, and adding an acceleration factor to it, and then setting the result of this
addition operation back into the original speed variable, so that the object’s
speed state now contains the new (accelerated) speed value.

void accelerateSpeed (int acceleration) {
speed = speed + acceleration;
}

   The .applyBrake( ) method takes the object’s speed state variable and
subtracts a braking factor from the current speed, which causes the object
to decelerate, or to brake. This is done by taking the object’s current speed
setting and subtracting a braking factor from it, and then setting the result of the
subtraction back to the original speed variable, so that the object’s speed state
now contains the updated (decelerated) braking value.

void applyBrake (int brakingFactor) {
speed = speed - brakingFactor;
}
Free download pdf