Java Reference
In-Depth Information
public boolean equals(Object x). Use this method to check if two objects
are equal to each other. This method is often overridden (method over-
riding is discussed in the next section) and allows a class to determine
what it means for two objects of that type to be equal. Note if two objects
are equal as determined by this method, then the hashcode() method of
the two objects should generate the same hash code.
protected Object clone() throws CloneNotSupportedException. The
clone method is used to create a copy of an object. The exception occurs
when the object being cloned does not support cloning. The details of
cloning objects are not discussed in this topic.
public String toString(). This method returns a string representation of
the object. Representing an object as a String can be helpful for debug-
ging or testing purposes. The Java documentation recommends that you
add the toString() method to all of your classes, a widely used practice in
Java programming.
protected void finalize() throws Throwable. This method is invoked on
an object right before the object is to be garbage collected. The finalize()
method allows for an object to free up any resources or perform any nec-
essary cleanup before the object is removed from memory.
public final void wait() throws InterruptedException. The wait()
method has two other overloaded versions in the Object class. Invoking
wait() on an object causes the current thread to stop executing until some
other thread invokes notify() on the same object. The wait() and notify()
methods are used for thread synchronization.
public final void notify(). There is also a notifyAll() method in the
Object class. These methods are used to restart any threads that were
blocked by invoking one of the wait() methods on the object.
The final methods in the Object class, such as wait() and notify(), cannot be
changed by the child classes of Object; however, the nonfinal methods are
intended to be included in classes that want or need to change the default
behavior of the corresponding method in the Object class.
For example, the default behavior of the toString() method in Object is to
print out the name of the class, followed by the @ symbol, followed by the
hashcode value. If you do not want this behavior, add toString() to your class
and generate any string you like.
The following ToStringDemo program invokes the toString() method of the
following Radio class. Notice the Radio class does not contain a toString()
method but inherits the default toString() method in Object.
Study the ToStringDemo program carefully and try to determine the output.
(Note that I added something that we have not discussed yet, printing out just
a reference.)
Search WWH ::




Custom Search