Generics · Topic 2 of 7
Generic classes
Definition​
A generic class works with a type that you choose when you use it, written like Box<String>. The compiler checks the type for you, so you do not need casts.
Example code​
A box that holds any one type, and a pair of two types
class Box<T> {
private T value;
void set(T value) { this.value = value; }
T get() { return value; }
}
class Pair<K, V> {
final K key;
final V value;
Pair(K key, V value) { this.key = key; this.value = value; }
}
class Demo {
public static void main(String[] args) {
Box<String> name = new Box<>();
name.set("Asha");
String text = name.get(); // no cast needed
System.out.println(text.toUpperCase());
Pair<String, Integer> age = new Pair<>("Asha", 30);
System.out.println(age.key + " is " + age.value);
// name.set(42); // compile error: the box only holds a String
}
}
// Output:
// ASHA
// Asha is 30
Finished this page? Track your progress (saved only in your browser).