The Object Class
java.lang.Object is the ancestor
of all objects; it’s the primordial class from which all other classes are
ultimately derived. Methods defined in Object are, therefore, very important because
they appear in every instance of every class, throughout all of Java. At
last count, there were nine public methods and two protected methods in
Object. Five of these are versions of
wait() and notify() that are used to synchronize threads on
object instances, as we’ll discuss in Chapter 9.
The remaining four methods are used for basic comparison, conversion, and
administration.
Every object has a toString() method that
can be called when it’s to be represented as a text value. PrintStream objects use toString() to print data, as discussed in Chapter 12. toString() is also used implicitly when an
object is referenced in a string concatenation. Here are some
examples:
MyObjmyObject=newMyObj();AnswertheAnswer=newAnswer();System.out.println(myObject);Strings="The answer is: "+theAnswer;
To be friendly, a new kind of object can override toString() and implement its own version that
provides appropriate information about itself. This is particularly
helpful in debugging, where it is common to print the string value of an
object to see what is going on. Two other methods, equals() and hashCode(), may also require specialization when
you create a new class.
Equality and Equivalence
equals() determines whether two objects are equivalent. Precisely what that means ...