Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

The next line assigns toiOba reference to an instance of anIntegerversion of theGen
class:


iOb = new Gen(88);


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. Thus, the reference returned bynewmust also be
of typeGen. If it isn’t, a compile-time error will result. For example, the following
assignment will cause a compile-time error:


iOb = new Gen(88.0); // Error!


BecauseiObis of typeGen, it can’t be used to refer to an object ofGen.
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(88);


makes use of autoboxing to encapsulate the value 88, which is anint, into anInteger. This
works becauseGencreates a constructor that takes anIntegerargument. Because
anIntegeris expected, Java will automatically box 88 inside one. Of course, the assignment
could also have been written explicitly, like this:


iOb = new Gen(new Integer(88));


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 strOb = new Gen("Generics Test");


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

Free download pdf