PART I
C h a p t e r 1 8 :
G e n e r i c s
517
PART IPART I
Because of the
new( )
constraint, any type argument must supply a parameterless
constructor.
Next, examine the
Test
constructor, shown here:
public Test() {
// This works because of the new() constraint.
obj = new T(); // create a T object
}
A new object of type
T
is created and a reference to it is assigned to
obj
. This statement is
valid only because the
new( )
constraint ensures that a constructor will be available. To
prove this, try removing the
new( )
constraint and then attempt to recompile the program.
As you will see, an error will be reported.
In
Main( )
, an object of type
Test
is instantiated, as shown here:
Test x = new Test();
Notice that the type argument is
Do'stlaringiz bilan baham: |