Java Reference
In-Depth Information
chain of references, it can be reclaimed at the discretion of the runtime system
if memory is low. It is possible that if memory does not run low, the virtual
machine will not attempt to reclaim these objects.
2.2.4 the meaning of =
Suppose we have two primitive variables lhs and rhs where lhs and rhs stand for
left-hand side and right-hand side, respectively. Then the assignment statement
lhs and rhs stand
for left-hand side
and right-hand side ,
respectively.
lhs = rhs;
has a simple meaning: The value stored in rhs is copied to the primitive
variable lhs . Subsequent changes to either lhs or rhs do not affect the other.
For objects, the meaning of = is the same: Stored values are copied. If lhs
and rhs are references (of compatible types), then after the assignment
statement, lhs will refer to the same object that rhs does. Here, what is being
copied is an address. The object that lhs used to refer to is no longer referred to
by lhs . If lhs was the only reference to that object, then that object is now unref-
erenced and subject to garbage collection. Note that the objects are not copied.
Here are some examples. First, suppose we want two Button objects. Then
suppose we try to obtain them first by creating noButton . Then we attempt to
create yesButton by modifying noButton as follows:
For objects, = is a
reference assign-
ment, rather than
an object copy.
Button noButton = new Button( "No" );
Button yesButton = noButton;
yesButton.setLabel( "Yes" );
p.add( noButton );
p.add( yesButton );
This does not work because only one Button object has been constructed. Thus
the second statement simply states that yesButton is now another name for the
constructed Button at line 1. That constructed Button is now known by two
names. On line 3, the constructed Button has its label changed to Yes , but this
means that the single Button object, known by two names, is now labeled Yes .
The last two lines add that Button object to the Panel p twice.
The fact that yesButton never referred to its own object is immaterial in
this example. The problem is the assignment. Consider
Button noButton = new Button( "No" );
Button yesButton = new Button( );
yesButton = noButton;
yesButton.setLabel( "Yes" );
p.add( noButton );
p.add( yesButton );
 
Search WWH ::




Custom Search