Java Reference
In-Depth Information
figure 2.3
The result of call-by-
value. (a) b is a copy
of yesButton ; (b) after
b.setLabel("No") :
changes to the state
of the object
referenced by b are
reflected in the object
referenced by
yesButton because
these are the same
object; (c) after
b=null : change to the
value of b does not
affect the value of
yesButton ; (d) after
the method returns, b
is out of scope.
yesButton
(a)
Ye s
b
yesButton
(b)
No
b
yesButton
(c)
No
b = null
yesButton
(d)
No
Two reference types are equal via == if they refer to the same stored object
(or they are both null ). Consider, for example, the following:
Button a = new Button( "Yes" );
Button b = new Button( "Yes" );
Button c = b;
Here, we have two objects. The first is known by the name a , and the second is
known by two names: b and c . b==c is true . However, even though a and b are
referencing objects that seem to have the same value, a==b is false , since they
reference different objects. Similar rules apply for != .
Sometimes it is important to know if the states of the objects being refer-
enced are identical. All objects can be compared by using equals , but for
many objects (including Button ) equals returns false unless the two references
are referencing the same object (in other words, for some objects equals is no
more than the == test). We will see an example of where equals is useful when
the String type is discussed in Section 2.3.
The equals method
can be used to test
whether two refer-
ences reference
objects that have
identical states.
2.2.7 no operator overloading for objects
Except for the single exception described in the next section, new operators,
such as + , - , * , and / cannot be defined to work for objects. Thus there is no <
operator available for any object. Instead, a named method, such as lessThan ,
must be defined for this task.
 
Search WWH ::




Custom Search