Careeroza
Generic Classes
Writing a Generic Class
Example
Box<T> works for any type. Pair<K, V> has two type parameters.
public class Main {
public static void main(String[] args) {
Box<String> nameBox = new Box<>("Laptop");
Box<Integer> qtyBox = new Box<>(3);
String name = nameBox.get(); // no cast
int qty = qtyBox.get();
System.out.println(name + " x " + qty);
Pair<String, Double> price = new Pair<>("Laptop", 54999.0);
System.out.println(price);
Pair<Integer, Boolean> status = new Pair<>(404, false);
System.out.println(status.key() + " ok? " + status.value());
}
}
class Box<T> {
private final T value;
Box(T value) { this.value = value; }
T get() { return value; }
}
class Pair<K, V> {
private final K key;
private final V value;
Pair(K key, V value) { this.key = key; this.value = value; }
K key() { return key; }
V value() { return value; }
@Override public String toString() { return "(" + key + ", " + value + ")"; }
}Output
Laptop x 3 (Laptop, 54999.0) 404 ok? false
Generic Interfaces
interface Repository<T, ID> {
void save(T entity);
T findById(ID id);
List<T> findAll();
}
class ProductRepository implements Repository<Product, Long> {
// T = Product, ID = Long
...
}Note: Spring Data's JpaRepository<Product, Long> is exactly this idea.