The next line assigns toiOba reference to an instance of anIntegerversion of theGen
class:
iOb = new Gen
Notice that when theGenconstructor is called, the type argumentIntegeris also specified.
This is necessary because the type of the object (in this caseiOb) to which the reference is
being assigned is of typeGen
of typeGen
assignment will cause a compile-time error:
iOb = new Gen
BecauseiObis of typeGen
This type checking is one of the main benefits of generics because it ensures type safety.
As the comments in the program state, the assignment
iOb = new Gen
makes use of autoboxing to encapsulate the value 88, which is anint, into anInteger. This
works becauseGen
anIntegeris expected, Java will automatically box 88 inside one. Of course, the assignment
could also have been written explicitly, like this:
iOb = new Gen
However, there would be no benefit to using this version.
The program then displays the type ofobwithiniOb, which isInteger. Next, the program
obtains the value ofobby use of the following line:
int v = iOb.getob();
Because the return type ofgetob( )isT, which was replaced byIntegerwheniObwas
declared, the return type ofgetob( )is alsoInteger, which unboxes intointwhen assigned
tov(which is anint). Thus, there is no need to cast the return type ofgetob( )toInteger.
Of course, it’s not necessary to use the auto-unboxing feature. The preceding line could
have been written like this, too:
int v = iOb.getob().intValue();
However, the auto-unboxing feature makes the code more compact.
Next,GenDemodeclares an object of typeGen
Gen
Because the type argument isString,Stringis substituted forTinsideGen. This creates
(conceptually) aStringversion ofGen, as the remaining lines in the program demonstrate.
Chapter 14: Generics 319