Java Reference
In-Depth Information
sion of Gen was created. Thus, there is really only one version of Gen that actually ex-
ists in your program. The process of removing generic type information is called erasure ,
which is discussed later in this chapter.
The next line assigns to iOb a reference to an instance of an Integer version of the Gen
class.
Notice that when the Gen constructor is called, the type argument Integer is also specified.
This is because the type of the object (in this case iOb ) to which the reference is being as-
signed is of type Gen<Integer> . Thus, the reference returned by new must also be of type
Gen<Integer> . If it isn't, a compile-time error will result. For example, the following as-
signment will cause a compile-time error:
Because iOb is of type Gen<Integer> , it can't be used to refer to an object of
Gen<Double> . This type of checking is one of the main benefits of generics because it en-
sures type safety.
As the comments in the program state, the assignment
makes use of autoboxing to encapsulate the value 88, which is an int , into an Integer . This
works because Gen<Integer> creates a constructor that takes an Integer argument. Be-
cause an Integer is expected, Java will automatically box 88 inside one. Of course, the as-
signment could also have been written explicitly, like this:
However, there would be no benefit to using this version.
The program then displays the type of ob within iOb , which is Integer . Next, the pro-
gram obtains the value of ob by use of the following line:
Because the return type of getob( ) is T , which was replaced by Integer when iOb was
declared, the return type of getob( ) is also Integer , which auto-unboxes into int when as-
Search WWH ::




Custom Search