Java Reference
In-Depth Information
Methods are defined in a manner similar to a class. They begin with a statement that
names the method, the kind of information the method produces, and other things.
The
checkTemperature()
method is contained within the braces on lines 6 and 11 of
Listing 1.1. This method can be called on a
VolcanoRobot
object to find out its tempera-
ture.
1
This method checks to see whether the object's
temperature
instance variable has a
value greater than 660. If it does, two other instance variables are changed:
The
status
is changed to the text “returning home,” indicating that the temperature
is too hot and the robot is heading back to its base.
n
The speed is changed to 5. (Presumably, this is as fast as the robot can travel.)
n
The second instance method,
showAttributes()
, is defined in lines 13-17:
void showAttributes() {
System.out.println(“Status: “ + status);
System.out.println(“Speed: “ + speed);
System.out.println(“Temperature: “ + temperature);
}
This method calls
System.out.println()
to display the values of three instance vari-
ables along with some text explaining what each value represents.
Save the file when you're done entering the source code. You don't need to compile
it yet.
Running the Program
Even if you compiled the
VolcanoRobot
class successfully, you couldn't do anything
with it. The class you have created defines what a
VolcanoRobot
object would be like if
one were used in a program, but it doesn't create one of these objects.
There are two ways to put the
VolcanoRobot
class to use:
Create a separate Java program that uses the class.
n
Add a special class method called
main()
to the
VolcanoRobot
class so that it can
be run as an application and then use
VolcanoRobot
objects in that method.
n
The first option is chosen for this exercise. Listing 1.2 contains the source code for
VolcanoApplication
, a Java class that creates a
VolcanoRobot
object, sets its instance
variables, and calls methods.