Java Reference
In-Depth Information
The consequences are the same. Here, there are two
Button
objects that
have been constructed. At the end of the sequence, the first object is being
referenced by both
noButton
and
yesButton
, while the second object is
unreferenced.
At first glance, the fact that objects cannot be copied seems like a severe
limitation. Actually, it is not, although this does take a little getting used to.
(Some objects do need to be copied. For those, if a
clone
method is available,
it should be used. However,
clone
is not used in this text.)
2.2.5
parameter passing
Because of call-by-value, the actual arguments are sent into the formal param-
eters using normal assignment. If the parameter is a reference type, then we
know that normal assignment means that the formal parameter now references
the same object as does the actual argument. Any method applied to the for-
mal parameter is thus also being applied to the actual argument. In other lan-
guages, this is known as
call-by-reference parameter passing
. Using this
terminology for Java would be somewhat misleading because it implies that
the parameter passing is different. In reality, the parameter passing has not
changed; rather, it is the parameters that have changed, from nonreference
types to reference types.
As an example, suppose we pass
yesButton
as a parameter to the
clearButton
routine that is defined as follows:
Call-by-value
means that for ref-
erence types, the
formal parameter
references the
same object as
does the actual
argument.
public static void clearButton( Button b )
{
b.setLabel( "No" );
b = null;
}
Then, as Figure 2.3 shows,
b
references the same object as
yesButton
, and
changes made to the state of this object by methods invoked through
b
will be
seen when
clearButton
returns. Changes to the value of
b
(i.e., which object it
references) will not have any affect on
yesButton
.
2.2.6
the meaning of
==
For primitive types,
==
is true if the stored values are identical. For reference
types, its meaning is different but is perfectly consistent with the previous
discussion.
For reference
types,
==
is true
only if the two ref-
erences reference
the
same object
.
Search WWH ::
Custom Search