Generics
Box<T> ek generic class hai — T ek placeholder hai jo jahan bhi Box istemal hota hai wahan ek real type se fill ho jaata hai, isliye Box<Integer> aur Box<String> dono bilkul usi class ke valid, type-safe instantiations hain, compiler call site par koi bhi type mismatch pakarte hue.
public class Main {
static class Box<T> {
private T value;
Box(T value) {
this.value = value;
}
T getValue() {
return value;
}
}
public static void main(String[] args) {
Box<Integer> intBox = new Box<>(42);
Box<String> strBox = new Box<>("hello");
System.out.println(intBox.getValue());
System.out.println(strBox.getValue());
}
}42 hello
Generic methods
Ek method apne aap generic ho sakta hai, apni class se independent — return type se pehle <T>, first(T a, T b) declare karta hai jo kisi bhi single type T ke liye kaam karta hai, compiler call site par arguments se T infer karte hue, koi explicit type ki zaroorat nahi.
public class Main {
static <T> T first(T a, T b) {
return a;
}
public static void main(String[] args) {
System.out.println(first(10, 20));
}
}10
Aage: Collections Framework — HashMap aur HashSet, Java ke standard collection types mein se do.
Practice exercise
Ek generic class Box<T> define karein jiska ek value field ho aur ek getValue() method ho. Ek Box<String> banayein jisme "hello" ho, phir uska value print karein.