Java Reference
In-Depth Information
The Object Class
In Java, all classes are derived ultimately from the Object class. If a class defi-
nition doesn't use the extends clause to derive itself explicitly from another
class, then that class is automatically derived from the Object class by default.
Therefore, the following two class definitions are equivalent:
class Thing
{
// whatever
}
and
class Thing extends Object
{
// whatever
}
Because all classes are derived from Object , all public methods of
Object are inherited by every Java class. They can be invoked through
any object created in any Java program. The Object class is defined in
the java.lang package of the Java standard class library. Figure 9.5
lists some of the methods of the Object class.
KEY CONCEPT
All Java classes are derived, directly
or indirectly, from the Object class.
As it turns out, we've been using Object methods quite often in our exam-
ples. The toString method, for instance, is defined in the Object class, so the
toString method can be called on any object. As we've seen several times, when
a println method is called with an object parameter, toString is
called to determine what to print.
Therefore, when we define a toString method in a class, we are
actually overriding an inherited definition. The definition for toString
that is provided by the Object class returns a string containing the
KEY CONCEPT
The toString and equals methods
are inherited by every class in every
Java program.
boolean equals (Object obj)
Returns true if this object is an alias of the specified object.
String toString ()
Returns a string representation of this object.
Object clone ()
Creates and returns a copy of this object.
FIGURE 9.5 Some methods of the Object class
 
Search WWH ::




Custom Search