Java Reference
In-Depth Information
LISTING 1.1
Continued
13: void showAttributes() {
14: System.out.println(“Status: “ + status);
15: System.out.println(“Speed: “ + speed);
16: System.out.println(“Temperature: “ + temperature);
17: }
18: }
The
class
statement in line 1 of Listing 1.1 defines and names the
VolcanoRobot
class.
Everything contained between the opening brace (“{“) on line 1 and the closing brace
(“}”) on line 18 is part of this class.
The
VolcanoRobot
class contains three instance variables and two instance methods.
The instance variables are defined in lines 2-4:
String status;
int speed;
float temperature;
The variables are named
status
,
speed
, and
temperature
. Each is used to store a differ-
ent type of information:
status
holds a
String
object, a group of letters, numbers, punctuation, and other
characters.
n
speed
holds an
int
, an integer value.
n
temperature
holds a
float
, a floating-point number.
n
String
objects are created from the
String
class, which is part of the Java class library
and can be used in any Java program.
TIP
As you might have noticed from the use of
String
in this program,
a class can use objects as instance variables.
The first instance method in the
VolcanoRobot
class is defined in lines 6-11, reprinted
here:
void checkTemperature() {
if (temperature > 660) {
status = “returning home”;
speed = 5;
}
}