TheObject
class, in thejava.lang
package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of theObject
class. Every class you use or write inherits the instance methods ofObject
. You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. The methods inherited fromObject
that are discussed in this section are:
protected Object clone() throws CloneNotSupportedException
Creates and returns a copy of this object.public boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.protected void finalize() throws Throwable
Called by the garbage collector on an object when garbage
collection determines that there are no more references to the objectpublic final Class getClass()
Returns the runtime class of an object.public int hashCode()
Returns a hash code value for the object.public String toString()
Returns a string representation of the object.
The
notify
,notifyAll
, andwait
methods ofObject
all play a part in synchronizing the activities of independently running threads in a program, which is discussed in a later lesson and won't be covered here. There are five of these methods:
public final void notify()
public final void notifyAll()
public final void wait()
public final void wait(long timeout)
public final void wait(long timeout, int nanos)
Note: There are some subtle aspects to a number of these methods, especially theclone
method. You can get information on the correct usage of these methods in the book Effective Java by Josh Bloch.The clone() Method
If a class, or one of its superclasses, implements theCloneable
interface, you can use theclone()
method to create a copy from an existing object. To create a clone, you write:aCloneableObject.clone();Object
's implementation of this method checks to see whether the object on whichclone()
was invoked implements theCloneable
interface. If the object does not, the method throws aCloneNotSupportedException
exception. Exception handling will be covered in a later lesson. For the moment, you need to know thatclone()
must be declared asif you are going to write aprotected Object clone() throws CloneNotSupportedException -- or -- public Object clone() throws CloneNotSupportedExceptionclone()
method to override the one inObject
.If the object on which
clone()
was invoked does implement theCloneable
interface,Object
's implementation of theclone()
method creates an object of the same class as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables.The simplest way to make your class cloneable is to add
implements Cloneable
to your class's declaration. then your objects can invoke theclone()
method.For some classes, the default behavior of
Object
'sclone()
method works just fine. If, however, an object contains a reference to an external object, sayObjExternal
, you may need to overrideclone()
to get correct behavior. Otherwise, a change inObjExternal
made by one object will be visible in its clone also. This means that the original object and its clone are not independent—to decouple them, you must overrideclone()
so that it clones the object andObjExternal
. Then the original object referencesObjExternal
and the clone references a clone ofObjExternal
, so that the object and its clone are truly independent.The equals() Method
Theequals()
method compares two objects for equality and returnstrue
if they are equal. Theequals()
method provided in theObject
class uses the identity operator (==
) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. Theequals()
method provided byObject
tests whether the object references are equal—that is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the
equals()
method. Here is an example of aBook
class that overridesequals()
:Consider this code that tests two instances of thepublic class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; } }Book
class for equality:This program displaysBook firstBook = new Book("0201914670"); //Swing Tutorial, 2nd edition Book secondBook = new Book("0201914670"); if (firstBook.equals(secondBook)) { System.out.println("objects are equal"); } else { System.out.println("objects are not equal"); }objects are equal
even thoughfirstBook
andsecondBook
reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.You should always override the
equals()
method if the identity operator is not appropriate for your class.
Note: If you overrideequals()
, you must overridehashCode()
as well.The finalize() Method
TheObject
class provides a callback method,finalize()
, that may be invoked on an object when it becomes garbage.Object
's implementation offinalize()
does nothing—you can overridefinalize()
to do cleanup, such as freeing resources.The
finalize()
method may be called automatically by the system, but when it is called, or even if it is called, is uncertain. Therefore, you should not rely on this method to do your cleanup for you. For example, if you don't close file descriptors in your code after performing I/O and you expectfinalize()
to close them for you, you may run out of file descriptors.The getClass() Method
You cannot overridegetClass
.The
getClass()
method returns aClass
object, which has methods you can use to get information about the class, such as its name (getSimpleName()
), its superclass (getSuperclass()
), and the interfaces it implements (getInterfaces()
). For example, the following method gets and displays the class name of an object:Thevoid printClassName(Object obj) { System.out.println("The object's class is " obj.getClass().getSimpleName()); }Class
class, in thejava.lang
package, has a large number of methods (more than 50). For example, you can test to see if the class is an annotation (isAnnotation()
), an interface (isInterface()
), or an enumeration (isEnum()
). You can see what the object's fields are (getFields()
) or what its methods are (getMethods()
), and so on.The hashCode() Method
The value returned byhashCode()
is the object's hash code, which is the object's memory address in hexadecimal.By definition, if two objects are equal, their hash code must also be equal. If you override the
equals()
method, you change the way two objects are equated andObject
's implementation ofhashCode()
is no longer valid. Therefore, if you override theequals()
method, you must also override thehashCode()
method as well.The toString() Method
You should always consider overriding thetoString()
method in your classes.The
Object
'stoString()
method returns aString
representation of the object, which is very useful for debugging. TheString
representation for an object depends entirely on the object, which is why you need to overridetoString()
in your classes.You can use
toString()
along withSystem.out.println()
to display a text representation of an object, such as an instance ofBook
:which would, for a properly overriddenSystem.out.println(firstBook.toString());toString()
method, print something useful, like this:ISBN: 0201914670; The JFC Swing Tutorial; A Guide to Constructing GUIs, 2nd Edition