Java Reference
In-Depth Information
Rule #2
The Object class has nine methods, which are available to be used in all classes in Java. We can put the methods into
two categories.
Methods in the first category have been implemented in the Object class. You are supposed to use them as they
have been implemented. You cannot reimplement (the technical term for reimplement is override) these methods in
any class you create. Their implementation is final . Methods that fall into this category are getClass() , notify() ,
notifyAll() , and wait() .
Methods in the second category have a default implementation in the Object class. You can customize their
implementations by reimplementing them in your classes. Methods that fall into this category are toString() ,
equals() , hashCode() , clone() , and finalize() .
A Java programmer must understand the proper use of all of the methods in the Object class. I will discuss them
in detail, except the notify() , notifyAll() , and wait() methods. These methods are used in thread synchronization.
They will be discussed in a separate chapter on threads in the topic Beginning Java Language Features
(ISBN: 978-1-4302-6658-7). Table 7-1 lists all methods in the Object class with a brief description. The “Yes” in the
“Implemented” column indicates that the Object class has implementation for the method, which can be used
without writing any code. The “No” in this column means that you need to implement the method before using it. The
“Yes” in the “Customizable” column indicates that you can reimplement the method to customize it. The “No” in this
column indicates that the Object class has implemented the method and its implementation is final .
Table 7-1. List of Methods in the Object Class with Their Brief Description
Method
Implemented
Customizable
Description
public String toString()
Yes
Yes
It returns a string representation of
an object. Typically, it is used for
debugging purpose.
public boolean equals(Object obj)
Yes
Yes
It is used to compare two objects for
equality.
public int hashCode()
Yes
Yes
It returns a hash code (an integer)
value of an object.
protected Object clone() throws
CloneNotSupportedException
No
Yes
It is used to make a copy of an object.
protected void finalize() throws
Throwable
No
Yes
It is called by the garbage collector
before an object is destroyed.
public final Class getClass()
It returns a reference to the Class
object of the object.
Yes
No
public final void notify()
Yes
No
Notifies one thread in the wait queue
of the object.
public final void notifyAll()
Yes
No
Notifies all threads in the wait queue of
the object.
public final void wait()
throws InterruptedException
public final void wait(long timeout)
throws InterruptedException
public final void wait
(long timeout, int nanos)
throws InterruptedException
Yes
No
Makes a thread wait in the wait queue
of the object with or without a timeout.
 
 
Search WWH ::




Custom Search