Java Reference
In-Depth Information
Because all your classes inherit the methods defined in the Object class I explain the most important
ones in a little more detail.
The toString() Method
You have already made extensive use of the toString() method, and you know that it is used by the com-
piler to obtain a String representation of an object when necessary. It is obvious now why you 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 the Object class outputs 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:
It's Fido the Spaniel
Woof Woof
The second line here is generated by the toString() method implemented in the Object class. This is
inherited in the Animal class, and it is called because you no longer override it. The hexadecimal digits fol-
lowing the @ in the output are the hashcode of the object, which is produced by the hashcode() method that
is inherited from Object .
Obviously, knowing that toString( ) is inherited from Object in the Animal class, it would have been
appropriate to use the @Override annotation for the method in the Animal class.
Determining the Type of an Object
The getClass() method that all your classes inherit from Object returns an object of type Class that iden-
tifies the class of an object. Suppose you have a variable pet of type Animal that might contain a reference
to an object of type Dog , Cat , Duck , or even Spaniel . To figure out what sort of thing it really refers to, you
could write the following statements:
Class objectType = pet.getClass(); // Get the class type
System.out.println(objectType.getName()); // Output the class name
The method getName() is a member of the Class class, and it returns the fully qualified name of the
actual class of the object for which it is called as a String object. Thus, the second statement outputs the
name of the class for the pet object. If pet referred to a Duck object, this would output:
This is the fully qualified name in this case, as the class is in the default package, which has no name. For
a class defined in a named package, the class name would be prefixed with the package name. If you just
wanted to output the class identity, you need not explicitly store the Class object. You can combine both
statements into one:
System.out.println(pet.getClass().getName()); // Output the class name
Search WWH ::

Custom Search