Sub topic 2
Writing Your First Generic Class
In the last chapter, a raw List let any object in. The mistake only showed up when the program crashed. A generic class fixes this. It lets the compiler check the types for you.
What Is a Generic Class?
A generic class is a class that takes a type as an input. You write the class once. Then each user of the class picks the type it should hold.
A type parameter is a placeholder name for that type. You put it in angle brackets after the class name, like <T>. Inside the class, you use T the same way you would use String or Integer.
A type argument is the real type someone puts in place of T, such as String.
A Worked Example: Box
Here is a class that holds one value of any type.
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
public void set(T value) {
this.value = value;
}
}The T shows up in three places: the field, the constructor, and the methods. The class does not know what T will be, and it does not need to know.
Using the Box
Now create boxes with different type arguments. Save this next to Box.java.
public class BoxDemo {
public static void main(String[] args) {
Box<String> word = new Box<String>("hi");
String s = word.get(); // no cast needed
System.out.println(s.toUpperCase());
Box<Integer> number = new Box<Integer>(7);
int n = number.get() + 1;
System.out.println(n);
// word.set(5); // compile error: 5 is not a String
}
}Compile and run it:
javac Box.java BoxDemo.java
java BoxDemoThe output is HI and then 8.
Box<String> means "a Box where T is String." For that box, get() returns a String, so you need no cast. If you remove the // before word.set(5);, the code will not compile. The compiler catches the error before the program ever runs.
How the Compiler Sees It
You write the class once. The compiler then checks each use with the type you chose.
Common Beginner Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `Box<int>` | Compile error | Use `Box<Integer>` |
| Forgetting `<T>` after the class name | `T` is unknown | Write `class Box<T>` |
| Using `Box` with no type argument | It becomes a raw type, and you lose type checks | Always give a type argument |
Exercise
Given Box<Double> price = new Box<Double>(9.99);, what type does price.get() return, and does price.set("free"); compile?
Show answer
price.get() returns Double. price.set("free"); does not compile, because set on this box only accepts a Double.
Exercise
Write the field and getter for a generic class Holder<T> that stores one item named item.
Show answer
private T item; and public T getItem() { return item; } inside public class Holder<T> { ... }.