Java Reference
In-Depth Information
This program generates the following output:
The
sameBlock( )
and
sameVolume( )
methods compare the
Block
object passed as a
parameter to the invoking object. For
sameBlock( )
, the dimensions of the objects are com-
pared and
true
is returned only if the two blocks are the same. For
sameVolume( )
, the two
blocks are compared only to determine whether they have the same volume. In both cases,
notice that the parameter
ob
specifies
Block
as its type. Although
Block
is a class type cre-
ated by the program, it is used in the same way as Java's built-in types.
How Arguments Are Passed
As the preceding example demonstrated, passing an object to a method is a straightforward
task. However, there are some nuances of passing an object that are not shown in the ex-
ample. In certain cases, the effects of passing an object will be different from those experi-
enced when passing non-object arguments. To see why, you need to understand in a general
sense the two ways in which an argument can be passed to a subroutine.
The first way is
call-by-value
. This approach copies the
value
of an argument into the
formal parameter of the subroutine. Therefore, changes made to the parameter of the sub-
routine have no effect on the argument in the call. The second way an argument can be
passed is
call-by-reference
. In this approach, a reference to an argument (not the value of
the argument) is passed to the parameter. Inside the subroutine, this reference is used to
access the actual argument specified in the call. This means that changes made to the para-
meter
will
affect the argument used to call the subroutine. As you will see, although Java
uses call-by-value to pass arguments, the precise effect differs between whether a primitive
type or a reference type is passed.
When you pass a primitive type, such as
int
or
double
, to a method, it is passed by value.
Thus, a copy of the argument is made, and what occurs to the parameter that receives the
argument has no effect outside the method. For example, consider the following program: