Java Reference
In-Depth Information
b.j = 5;
a.anotherMethod (b);
int i = b.j; // i still holds 5, not 100
...
The j member of that new BClass is assigned the value 100. Back in the call-
ing code, the original b.j still holds the original value 5. The reason is that the
assignment of 100 to bb.j applied to a completely new instance of BClass ,
and, since the original reference was passed by value, that reference was not
changed. The calling code's b variable still references the original BClass
instance.
Comparison of reference variables only tests if the two variables refer to the
same object. That is, the test
if (a == b) statement;
simply checks whether a and b refer to the same object, not whether the referenced
objects have equal data values.
If you need to test whether two objects hold the same data values, many classes
provide an equals() method like this:
a.equals (b)
It returns true if the data in object b matches that in object a . Comparing
all the data inside an object for equality with an equals() method is called
a “deep” comparison, whereas the == comparison is “shallow.” In fact, all
classes implicitly include a shallow equals() method inherited from the top-
level class known as java.lang.Object (we discuss inheritance in Chapter 4).
However, unless the author of a class has explicitly written the equals() method
to do a deep comparison, the results may not be as expected. All classes in the
core Java libraries can be expected to have a properly written equals() method.
However, no such guarantees exist for third-party classes or classes you write
yourself unless you are careful to write your equals() method correctly.
3.7 Wrappers
We noted earlier that Java primitive types are not class objects. The language
designers decided that the higher processing speed and memory efficiency of
simple, non-class structures for such heavily used data types overruled the ele-
gance of a purely object only language. They decided instead that for each prim-
itive type there would be a corresponding wrapper class that provides various
useful tools such as methods for converting a given numerical type to a string or
a string to a number.
 
Search WWH ::




Custom Search