Java Reference
In-Depth Information
Display 14.6
Using Our Ordered Pair Class (part 2 of 2)
second: words
The secret words are
first: Happy
second: Day
PITFALL: A Generic Constructor Name Has No Type Parameter
The class name in a parameterized class definition has a type parameter attached, such as
Pair<T> in Display 14.5. This can mislead you into thinking you need to use the type
parameter in the heading of the constructor definition, but you do not repeat the type param-
eter specification <T> in the heading of the constructor definition. For example, you use
public Pair()
You do not use
public Pair<T>()
A constructor can use the type parameter, such as T , as the type for a parameter for the
constructor, as in the following, but the constructor heading does not include the type
parameter in angular brackets, such as <T> :
public Pair(T firstItem, T secondItem)
For a complete example, see Display 14.5.
Sometimes it seems that people stay up late at night thinking of ways to make things
confusing. As we just noted, in the definition of a parameterized class, a constructor has
no type parameter in angular brackets. So, you see the following in Display 14.5:
public Pair(T firstItem, T secondItem)
But as shown in Display 14.6, when you instantiate a generic class by specifying a type
for the type parameter, you do specify the type in angular brackets when writing the
constructor name, as in the following from Display 14.6:
Pair<String> secretPair =
new Pair<String>("Happy", "Day");
However, this second case is not hard to remember. If you left out the <String> , Java
would not know which Pair class you meant. If you left out the <String> , the compiler
could not tell if you meant Pair<String> , Pair<Double> , or some other Pair class.
 
Search WWH ::




Custom Search