A (175)

(Tuis.) #1
CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces 141

   The .turnWheel( ) method is straightforward, much like the .shiftGears()
method, except that it uses a string value of N, S, E, or W to control the direction
that the car turns. When .turnWheel("W") is used, the car will turn to the left,
when .turnWheel(“E”) is used, the car will turn to the right, given, of course, that
the Car object is currently heading to the north, which according to its default
direction setting, it is.

void turnWheel (String newDirection) {
direction = newDirection;
}

The methods that make the Car object function go inside the class and after the variable
declarations, as follows:


class Car {
int speed = 15;
int gear = 1;
int drivetrain = 4;
String direction = "N";
String color = "Red";
String fuel = "Gas";


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


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


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


void turnWheel (String newDirection) {
direction = newDirection;
}
}


This Car class allows us to define a Car object, but only if we include a Car( ) constructor method,
covered in the next section of this chapter.


Constructor Methods: The Java Object Blueprint


If you want to be able to make an object with preset values out of your class definition, then you
need to include what is called a constructor method. This method needs to be named the same as
the class name, in this case it would be the Car( ) method, and should be the first method that is
defined inside of the class construct, after the variable definitions.

Free download pdf