Java Reference
In-Depth Information
Adding a Method to the Vehicle Class
As just explained, the methods of a class typically manipulate and provide access to the
data of the class. With this in mind, recall that
main( )
in the preceding examples computed
the range of a vehicle by multiplying its fuel consumption rate by its fuel capacity. While
technically correct, this is not the best way to handle this computation. The calculation of
a vehicle's range is something that is best handled by the
Vehicle
class itself. The reason
for this conclusion is easy to understand: the range of a vehicle is dependent upon the ca-
pacity of the fuel tank and the rate of fuel consumption, and both of these quantities are
encapsulated by
Vehicle
. By adding a method to
Vehicle
that computes the range, you are
enhancing its object-oriented structure. To add a method to
Vehicle
, specify it within
Ve-
hicle
's declaration. For example, the following version of
Vehicle
contains a method called
range( )
that displays the range of the vehicle.