Chapter 4. Declarations
This chapter discusses how to declare a generic class. It describes constructors, static members, and nested classes, and it fills in some details of how erasure works.
Note
The code examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/blob/main/src/main/java/org/jgcbook/chapter04
Constructors
In a generic class, type parameters appear in the header that declares the class, but not in the constructor:
classPair<T,U>{ private final T first; private final U second; publicPair(T first, U second) { this.first = first; this.second = second; } public T getFirst() { return first; } public U getSecond() { return second; } }
The type parameters T and U are declared at the beginning of the class, not in the constructor, but actual type arguments are passed to the constructor whenever it is invoked:
Pair<String, Integer> pair1 = new Pair<String, Integer>("one", 2);
assert pair1.getFirst().equals("one") && pair1.getSecond() == 2;
A common mistake is to forget the type parameters when invoking the constructor:
Pair pair2 = new Pair<String, Integer>("one", 2);
This mistake produces a warning when compiled with the option -Xlint, which enables detailed warnings:
% javac -Xlint Pair.java Pair.java:18: warning: [rawtypes] found raw type: Pair Pair pair2 = new Pair<String, Integer>("one", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access