Java Reference
In-Depth Information
To illustrate classes, we will develop a class that encapsulates information about vehicles,
such as cars, vans, and trucks. This class is called
Vehicle
, and it will store three items of
information about a vehicle: the number of passengers that it can carry, its fuel capacity,
and its average fuel consumption (in miles per gallon).
The first version of
Vehicle
is shown next. It defines three instance variables:
passen-
gers
,
fuelcap
, and
mpg
. Notice that
Vehicle
does not contain any methods. Thus, it is cur-
rently a data-only class. (Subsequent sections will add methods to it.)
A
class
definition creates a new data type. In this case, the new data type is called
Ve-
hicle
. You will use this name to declare objects of type
Vehicle
. Remember that a
class
declaration is only a type description; it does not create an actual object. Thus, the preced-
ing code does not cause any objects of type
Vehicle
to come into existence.
To actually create a
Vehicle
object, you will use a statement like the following:
After this statement executes,
minivan
will be an instance of
Vehicle
. Thus, it will have
“physical” reality. For the moment, don't worry about the details of this statement.
Each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class. Thus, every
Vehicle
object will
contain its own copies of the instance variables
passengers
,
fuelcap
, and
mpg
. To access
these variables, you will use the dot (.) operator. The
dot operator
links the name of an ob-
ject with the name of a member. The general form of the dot operator is shown here:
object.member
Thus, the object is specified on the left, and the member is put on the right. For example,
to assign the
fuelcap
variable of
minivan
the value 16, use the following statement:
In general, you can use the dot operator to access both instance variables and methods.
Here is a complete program that uses the
Vehicle
class: