Java Reference
In-Depth Information
default before we wrote its toString method. This default message was the behavior
of the Object class's toString method, which we inherited in our Point class. The
Object class provides a generic toString output that will work for every class: the
class name followed by some internal numeric information about the object. When
we wrote our own toString method, we overrode this default behavior.
It is sometimes useful to refer to the Object class in your programs. For example,
if you wish to write a method that can accept any object as a parameter, you can
declare a parameter of type Object :
// this method can accept any object as its parameter
public static void myMethod(Object o) {
...
}
Of course, since your parameter can be anything, you are only allowed to call the
methods from the Object class on it, such as toString or getClass . It is also legal
to have a method whose return type is Object .
The Object class is used extensively in the Java class libraries. For example, the
println method of the PrintStream class (the class of which System.out is an
instance) accepts a parameter of type Object , which allows you to print any object to
the console.
The equals Method
For several chapters now, you have used the == operator to compare for equality. You
have seen that this operator does not behave as expected when used on objects,
because it is possible to have two distinct objects with equivalent states, such as two
Point objects with the coordinates (5, 2). This observation is a reminder that an
object has an identity and is distinct from other objects, even if another object hap-
pens to have the same state.
A nonprogramming analogy would be if you and your friend both purchased iden-
tical pairs of shoes. They are in some ways equivalent, but you still consider them
distinct and separate items. You might not want to share them. And the items' states
are not linked in any way. Over time, their state might become visibly unequal, such
as if one of you wore your new shoes more often than the other.
The == operator does not behave as expected with objects because it tests whether
two objects have the same identity. The == comparison actually tests whether two
variables refer to the same object, not whether two distinct objects have the same
state. Consider the following three variable declarations:
Point p1 = new Point(7, 2);
Point p2 = new Point(7, 2);
Point p3 = p2;
The following diagram represents the state of these objects and the variables that
refer to them. Notice that p3 is not a reference to a third object but a second reference
 
Search WWH ::




Custom Search