|
|
More Features of the Java Language |
TheObjectclass sits at the top of the class hierarchy tree in the Java platform. Every class in the Java system is a descendent, direct or indirect, of the
Objectclass. This class defines the basic state and behavior that all objects must have, 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.Your classes may want to override the following
Objectmethods:Your class cannot override these
cloneequalsfinalizehashCodetoStringObjectmethods (they are final):
getClassnotifynotifyAllwaitThe
cloneMethodYou use theclonemethod to create objects from other objects of the same type. By default, objects are not cloneable, soObject's implementation of this method throws aCloneNotSupportedException. If you want your class to be cloneable, you must implement theCloneableinterface and override this method.Your version of the
clonemethod must provide for a field-by-field copy of the object being cloned. Here's a partial listing of a new version of theStackclass that implements theCloneableinterface and overrides theclonemethod (changes are indicated with a change in font):The implementation forpublic class Stack implements Cloneable { private Vector items; // code for Stack's methods and constructor not shown protected Object Clone() { try { Stack s = (Stack)super.clone(); s.items = (Vector)items.clone(); return s; } catch (CloneNotSupportedException e) { // this shouldn't happen because Stack is Cloneable throw new InternalError(); } } }Stack'sclonemethod is relatively simple because it can callObject's implementation of theclonemethod. Also, the only member ofStack, aVector, is also cloneable. Be careful:cloneshould not usenewto create the clone and should not call constructors.The
equalsMethodYou use theequalsmethod to compare two objects for equality. This method returnstrueif the objects are equal,falseotherwise. Note that equality does not necessarily mean that the objects are the same object. Consider this code that tests twoIntegers,oneandanotherOne, for equality:This program displaysInteger one = new Integer(1), anotherOne = new Integer(1); if (one.equals(anotherOne)) System.out.println("objects are equal");objects are equaleven thoughoneandanotherOnereference two distinct objects. They are considered equal because they contain the same integer value.Your classes should override the
equalsmethod to provide an appropriate equality test. Yourequalsmethod should compare the contents of the objects to see if they are functionally equivalent and returntrueif they are.The
finalizeMethodTheObjectclass provides a method,finalize, that cleans up an object before it is garbage collected. This method's role during garbage collection was discussed previously in Cleaning Up Unused Objects. Also, Writing afinalizeMethod showed you how to override thefinalizemethod to handle the finalization needs for your classes.The
hashCodeMethod[PENDING: under construction]The
toStringMethodObject'stoStringmethod returns aStringrepresentation of the object. You can usetoStringalong withSystem.out.printlnto display a text representation of an object, such as the current thread:TheSystem.out.println(Thread.currentThread().toString());Stringrepresentation for an object depends entirely on the object. TheStringrepresentation of anIntegerobject is the integer value displayed as text. TheStringrepresentation of aThreadobject contains various attributes about the thread, such as its name and priority. For example, the previous line of code displays the following output:TheThread[main,5,main]toStringmethod is very useful for debugging. It behooves you to override this method in all your classes.The
getClassMethodThegetClassmethod is a final method that returns a runtime representation of the class of this object. This method returns aClassobject. You can query theClassobject for various information about the class, such as its name, its superclass, and the names of the interfaces that it implements. The following method gets and displays the class name of an object:One handy use of thevoid PrintClassName(Object obj) { System.out.println("The Object's class is " + obj.getClass().getName()); }getClassmethod is to create a new instance of a class without knowing what the class is at compile time. The following sample method creates a new instance of the same class asobj, which can be any class that inherits fromObject(which means that it could be any class):Object createNewInstanceOf(Object obj) { return obj.getClass().newInstance(); }
Note: You also can get aClassobject from a class name using a class literal. For example, to get theClassobject for theStringclass useString.class. This is equivalent to, but more efficient than, callingClass.forName(String).
The
notify,notifyAll, andwaitMethodsYou cannot overrideObject'snotifyandnotifyAllmethods and its three versions ofwait. This is because they are critical for ensuring that threads are synchronized. The use of these methods is covered in Doing Two or More Tasks at Once: Threads. Take particular note of the section titled Synchronizing Threads
.
|
|
More Features of the Java Language |