Java Reference
In-Depth Information
It should be clear now why we could get polymorphic behavior with
toString()
in our derived
classes when our base class did not define the method. There is always a
toString()
method in all
your classes that is inherited from
Object
.
The two
protected
methods your classes inherit from
Object
are:
Method
Purpose
clone()
This will create an object that is a copy of the current object regardless of type.
This can be of any type as an
Object
variable can refer to an object of any
class. Note that this does not work with all class objects and does not always do
precisely what you want, as we will see later in this section.
finalize()
This is the method that is called to clean up as an object is destroyed. As you
have seen in the last chapter you can override this to add your own clean-up
code.
Since all your classes will inherit the methods defined in the
Object
class we should look at them in a
little more detail.
The toString() Method
We have already made extensive use of the
toString()
method and you know that it is used by the
compiler to obtain a
String
representation of an object when necessary. It is obvious now why we
must always declare the
toString()
method as
public
in a class. It is declared as such in the
Object
class and you can't declare it as anything else.
You can see what the
toString()
method, that is inherited from class
Object
, will output for an
object of one of your classes by commenting out the
toString()
method in
Animal
class in the
previous example. A typical sample of the output for an object is:
Your choice:
Spaniel@b75778b2
It's Fido the Spaniel
Woof Woof
The second line here is generated by the
toString()
method implemented in the
Object
class. This
will be inherited in the
Animal
class, and it is called because we no longer override it. The
hexadecimal digits following the
@
in the output are the hash code of the object.
Determining the Type of an Object
The
getClass()
method, that all your classes inherit from
Object,
will return an object of type
Class
that identifies the class of an object. Suppose you have a variable
pet
, of type
Animal
, that
might refer to an object of type
Dog
,
Cat
,
Duck
, or even
Spaniel
. To figure out what sort of thing it
really is, you could write the following statements:
Class objectType = pet.getClass(); // Get the class type
System.out.println(objectType.getName()); // Output the class name