Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
TheObject
class sits at the top of the class hierarchy tree. Every class is a descendent, direct or indirect, of theObject
class. This class defines the basic state and behavior that all objects might use, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the class of the object.The
Object
class provides several useful methods that may need to be overridden by a well-behaved subclass.In addition, the
equals
andhashCode
toString
Object
class provides the following handy methods:And then there is
getClass
notify
,notifyAll
, andwait
finalize
, a special method, called by the garbage collector. It shouldn't be called from regular programs.With the exception of
notify
,notifyAll
, andwait
, these methods are covered in the sections that follow. Thenotify
,notifyAll
, andwait
methods all play a part in synchronizing the activities of independently running threads in a program, which is discussed in Threads: Doing Two or More Tasks at Once.
You use the
Note: Use great care when implementing aclone
method. Implementing aclone
method properly can be tricky and has some non-trivial consequences. This section covers the method briefly, but you can find more information about the ins and outs of implementingclone
in the book Effective Java by Josh Bloch.clone
method to create an object 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
. Even thoughObject
implements theclone
method, theObject
class is not declared to implement theCloneable
interface, so classes that don't explicitly implement the interface are not cloneable. If the object on whichclone
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, then, is to add
implements
Cloneable
to your class's declaration. For some classes, the default behavior ofObject
'sclone
method works just fine. Other classes need to overrideclone
to get correct behavior.Consider a
Stack
class that contains anArrayList
and a member variable referencing its top element. IfStack
relies onObject
's implementation ofclone
, the original stack and its clone refer to the same list. Changing one stack changes the other, which is undesirable behavior.Here is an appropriate implementation of
clone
for ourStack
class, which clones the list to ensure that the original stack and its clone do not refer to the same list:The implementation forpublic class Stack implements Cloneable { private ArrayList<Object> items; ... //Code for Stack's methods and constructor //not shown. protected Stack clone() { try { //Clone the stack. Stack s = (Stack)super.clone(); //Clone the list. s.items = (ArrayList)items.clone(); return s; //Return the clone. } catch (CloneNotSupportedException e) { //This shouldn't happen because Stack and //ArrayList implement Cloneable. throw new AssertionError(); } } }Stack
'sclone
method is relatively simple. First, it callsObject
's implementation of theclone
method by callingsuper.clone
, which creates and initializes aStack
object. At this point, the original stack and its clone refer to the same list. Next, the method clones the list.
Note: Theclone
method should never usenew
to create the clone and should not call constructors. Instead, the method should callsuper.clone
, which creates an object of the correct type and allows the hierarchy of superclasses to perform the copying necessary to get a proper clone.
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. If the objects compared are the exact same object, the method returnstrue
.However, for some classes, two distinct objects of that type might be considered equal if they contain the same information. Here is an example of a
Book
class that, like a good citizen, overridesequals
:Consider this code that tests two instances of thepublic class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) { if (((Book)obj).getISBN().equals(this.ISBN)) { return true; } else { return false; } } 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.format("objects are equal%n"); } else { System.out.format("objects are not equal%n"); }objects are equal
even thoughfirstBook
andsecondBook
reference two distinct objects. They are considered equal because the objects compared contain the same value.You should always override the
equals
method if the identity operator is not appropriate for your class. If you overrideequals
, overridehashCode
as well.The value returned by
hashCode
is an int that maps an object into a bucket in a hash table. An object must always produce the same hash code. However, objects can share hash codes (they aren't necessarily unique). Writing a "correct" hashing function is easy always return the same hash code for the same object. Writing an "efficient" hashing function one that provides a sufficient distribution of objects over the buckets is difficult and is outside the scope of this tutorial.Even so, the hashing function for some classes is relatively obvious. For example, an obvious hash code for an
Integer
object is its integer value.For more information on writing correct implementations of
equals
andhashcode
, see Effective Java by Josh Bloch.
TheObject
class provides a callback method,finalize
, that allows you to clean up an object before it is garbage collected. Thefinalize
method may be called automatically by the system, and this is where you put any necessary cleanup code.
Note: You should not employ sloppy programming practices and then rely on this method to do your cleanup for you. For example, say you forget to close a file descriptor after performing some I/O. You don't know when or even if garbage collection will occur (when this method would be called) and you may run out of file descriptors before you run out of memory.For more information the dangers and subtleties of
finalize
, see Effective Java by Josh Bloch.
TheObject
'stoString
method returns aString
representation of the object. You can usetoString
along withSystem.out.format
to display a text representation of an object, such as an instance ofBook
:which would, hopefully, print something useful, like this:System.out.format("%s%n", firstBook.toString());The0201914670: The JFC Swing Tutorial: A Guide to Constructing GUIs, 2nd Edition Authors: Kathy Walrath, Mary Campione, Alison Huml, Sharon ZakhourString
representation for an object depends entirely on the object. ThetoString
method is very useful for debugging. You should override this method in all your classes.
ThegetClass
method returns a runtime representation of the class of an object. This method returns aClass
object, which you can query for information about the class, such as its name, its superclass, and the interfaces it implements. You cannot overridegetClass
. The following method gets and displays the class name of an object:One easy way to get avoid printClassName(Object obj) { //The getSimpleName method was introduced in J2SE 5.0. //Prior to that, you can use getName, which returns //the fully qualified name, rather than just the //class name. System.out.format("The object's class is %s.%n" obj.getClass().getSimpleName()); }Class
object is from its class name. Here are two ways to get theClass
object for theString
class:String.class Class.forName("java.lang.String")String.class
is preferred for performance reasons because it does the lookup only once.Class.forName
performs the lookup each time, but can be used even when the class name is not known at compile time.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.