Java Reference
In-Depth Information
This program contains several interesting things. First, a raw type of the generic
Gen
class is created by the following declaration:
Notice that no type arguments are specified. In essence, this creates a
Gen
object whose
type
T
is replaced by
Object
.
A raw type is not type safe. Thus, a variable of a raw type can be assigned a reference
to any type of
Gen
object. The reverse is also allowed, in which a variable of a specific
Gen
type can be assigned a reference to a raw
Gen
object. However, both operations are
potentially unsafe because the type checking mechanism of generics is circumvented.
This lack of type safety is illustrated by the commented-out lines at the end of the pro-
gram. Let's examine each case. First, consider the following situation:
In this statement, the value of
ob
inside
raw
is obtained, and this value is cast to
Integer
.
The trouble is that
raw
contains a
Double
value, not an integer value. However, this cannot
be detected at compile time because the type of
raw
is unknown. Thus, this statement fails
at run time.
The next sequence assigns to
strOb
(a reference of type
Gen<String>
) a reference to a
raw
Gen
object:
The assignment itself is syntactically correct, but questionable. Because
strOb
is of type
Gen<String>
, it is assumed to contain a
String
. However, after the assignment, the object
referred to by
strOb
contains a
Double
. Thus, at run time, when an attempt is made to as-
sign the contents of
strOb
to
str
, a run-time error results because
strOb
now contains a
Double
. Thus, the assignment of a raw reference to a generic reference bypasses the type-
safety mechanism.
The following sequence inverts the preceding case:
Here, a generic reference is assigned to a raw reference variable. Although this is syntactic-
ally correct, it can lead to problems, as illustrated by the second line. In this case,
raw
now