Java Reference
In-Depth Information
}
Directory "TestClassTypes"
This code produces the following output:
numbers class name LinkedList
proverbs class name LinkedList
Compare Class objects: true
How It Works
You call the
getClass()
method that is inherited from the
Object
class to obtain the
Class
objects
for the objects referenced by
proverbs
and
numbers
. You then call the
getName()
method for the
Class
object to get the runtime type name. In both instances the type name is
LinkedList
. The fact
that the runtime types are identical is further confirmed by the comparison of the
Class
objects for the
LinkedList<String>
and
LinkedList<Double>
objects, and the output shows they are identical.
Thus, you have the unavoidable conclusion that all instances of a given type share the same
Class
object
at runtime, and therefore the same runtime type. Of course, this does not mean that the objects are the
same type. For example, the following statement does not compile:
proverbs = (LinkedList<String>)numbers; // Illegal cast - will not
compile
The compiler knows that these objects are really of different types and does not allow you to do this.
However, not a lot prevents you from doing the following:
Object obj = (Object)numbers;
proverbs = (LinkedList<String>)obj; // Will result in a
compiler warning
Here the cast of
numbers
to type
Object
is legal — every class has
Object
as a base so the compiler
allows this. With the second statement, though, the compiler knows only that you are casting a reference
of type
Object
and therefore cannot identify this as an illegal operation. However, you will get a warning
about unsafe operations.
At runtime this operation is not checked because the runtime type of the reference stored in
obj
is
LinkedList
, the same as that of
proverbs
. This means that you end up with a reference to an object that
is really of type
LinkedList<Double>
in a variable of type
LinkedList<String>
. You discover that this
is a problem only when you attempt to call methods for the object. If you want to verify that this is the
case, you can add the following code to the end of the example:
Object obj = (Object)numbers;
System.out.println("obj class name " + obj.getClass().getName());
proverbs = (LinkedList<String>)obj;
System.out.println("obj in proverbs class name " +
obj.getClass().getName());
After some warnings from the compiler the example then produces the following output when you ex-
ecute it: