Methods in Java
Methods in Java
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
This program generates the following output, which is the same
as the previous version.
Volume is 3000.0
Volume is 162.0
Look closely at the following two lines of code:
mybox1.volume();
mybox2.volume();
The first line here invokes the volume( ) method on mybox1.
That is, it calls volume( )
relative to the mybox1 object, using the objects name
followed by the dot operator. Thus,
the call to mybox1.volume( ) displays the volume of the box
defined by mybox1, and the
call to mybox2.volume( ) displays the volume of the box
defined by mybox2. Each time
volume( ) is invoked, it displays the volume for the specified
box.
If you are unfamiliar with the concept of calling a method, the
following discussion will
help clear things up. When mybox1.volume( ) is executed,
the Java run-time system transfers
control to the code defined inside volume( ). After the
statements inside volume( ) have
executed, control is returned to the calling routine, and
execution resumes with the line of
code following the call. In the most general sense, a method is
Javas way of implementing
subroutines.
There is something very important to notice inside the volume(
) method: the instance
variables width, height, and depth 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