Java Reference
In-Depth Information
Let's look at the key elements of this program, beginning with the range( ) method itself.
The first line of range( ) is
This line declares a method called range that has no parameters. Its return type is void .
Thus, range( ) does not return a value to the caller. The line ends with the opening curly
brace of the method body.
The body of range( ) consists solely of this line:
This statement displays the range of the vehicle by multiplying fuelcap by mpg . Since each
object of type Vehicle has its own copy of fuelcap and mpg , when range( ) is called, the
range computation uses the calling object's copies of those variables.
The range( ) method ends when its closing curly brace is encountered. This causes pro-
gram control to transfer back to the caller.
Next, look closely at this line of code from inside main( ) :
This statement invokes the range( ) method on minivan . That is, it calls range( ) relative to
the minivan object, using the object's name followed by the dot operator. When a method
is called, program control is transferred to the method. When the method terminates, con-
trol is transferred back to the caller, and execution resumes with the line of code following
the call.
In this case, the call to minivan.range( ) displays the range of the vehicle defined by
minivan . In similar fashion, the call to sportscar.range( ) displays the range of the vehicle
defined by sportscar . Each time range( ) is invoked, it displays the range for the specified
object.
There is something very important to notice inside the range( ) method: the instance
variables fuelcap and mpg are referred to directly, without preceding them with an object
name or the dot operator. When a method uses an instance variable that is defined by its
class, it does so directly, without explicit reference to an object and without use of the dot
operator. This is easy to understand if you think about it. A method is always invoked re-
lative to some object of its class. Once this invocation has occurred, the object is known.
Search WWH ::




Custom Search