Java Reference
In-Depth Information
The Universal Superclass
I must now reveal something I have been keeping from you. All the classes that you define are
subclasses by default - whether you like it or not. All your classes have a standard class, Object , as a
base, so Object is a superclass of every class. You never need to specify the class Object as a base in
the definition of your classes - it happens automatically.
There are some interesting consequences of having Object as a universal superclass. For one thing, a
variable of type Object can hold an object of any class type. This is useful when you want to write a
method that needs to handle objects of unknown type. You can use a variable of type Object as a
parameter to a method, to receive an object, and then include code in the method that figures out what
kind of object it actually is (we will see something of the tools that will enable you to do this a little later
in this chapter).
Of course, your classes will inherit members from the class Object . These all happen to be methods, of
which seven are public , and two are protected . The seven public methods are:
Method
Purpose
toString()
This method returns a String object that describes the current object. In
the inherited version of the method, this will be the name of the class,
followed by ' @ ' and the hexadecimal representation for the object. This
method is called automatically when you concatenate objects with
String variables using + . You can override this method in your classes
to return your own String object for your class.
equals()
This compares the object passed as an argument with the current object,
and returns true if they are the same object (not just equal - they must
be one and the same object). It returns false if they are different
objects, even if the objects have identical values for their data members.
getClass()
This method returns an object of type Class that identifies the class of
the current object. We will see a little more about this later in this
chapter.
hashCode()
This method calculates a hash code value for an object and returns it as
type int . Hash code values are used in classes defined in the package
java.util for storing objects in hash tables. We will see more about
this in Chapter 12.
notify()
This is used to wake up a thread associated with the current object. We
will discuss in Chapter 14 how threads work.
notifyAll()
This is used to wake up all threads associated with the current object. We
will also discuss this in Chapter 14.
wait()
This method causes a thread to wait for a change in the current object.
We will discuss this method in Chapter 14.
Note that getClass() , notify() , notifyAll() , and wait() cannot be overridden in your own
class definitions - they are 'fixed' with the keyword final in the class definition for Object (see the
section on the final modifier later in this chapter).
Search WWH ::




Custom Search