Java Reference
In-Depth Information
Try This 7-1 Extending the Vehicle Class
To illustrate the power of inheritance, we will extend the
Vehicle
class first developed in
Chapter 4
. As you should recall,
Vehicle
encapsulates information about vehicles, includ-
ing the number of passengers they can carry, their fuel capacity, and their fuel consumption
rate. We can use the
Vehicle
class as a starting point from which more specialized classes
are developed. For example, one type of vehicle is a truck. An important attribute of a truck
is its cargo capacity. Thus, to create a
Truck
class, you can extend
Vehicle
, adding an in-
stance variable that stores the carrying capacity. Here is a version of
Truck
that does this.
In the process, the instance variables in
Vehicle
will be made
private
, and accessor meth-
ods are provided to get and set their values.
1.
Create a file called
TruckDemo.java
and copy the last implementation of
Vehicle
from
Chapter 4
into the file:
2.
Create the
Truck
class as shown here: