RKTechGame | Java Generics Advanced Concepts

Generic Type Bounds

Generic types me hum type parameters ke upper bounds specify kar sakte hain taaki sirf certain subtype hi allowed ho.

// Upper bound example: T must be subclass of Number
class Box<T extends Number> {
  private T value;
  public Box(T value) { this.value = value; }
  public T getValue() { return value; }
}

Iska matlab ab Box<String> allowed nahi, sirf Number ya uske subclass allowed hain, jaise Integer, Double.

Lower Bounds and Wildcards

Wildcards ? generic me flexible type parameters provide karta hai:

List<? extends Number> list1; // Accepts List of Number or its subclasses
List<? super Integer> list2;     // Accepts List of Integer or its superclasses

Generic Methods with Multiple Type Parameters

public <T, U> void printPair(T first, U second) {
  System.out.println("First: " + first + ", Second: " + second);
}

Aap ek method me ek se adhik generic parameters le sakte hain.

Real World Example: Generic Container Class

class Container<T> {
  private T content;
  public void setContent(T content) { this.content = content; }
  public T getContent() { return content; }
}

public class GenericsAdvancedDemo {
  public static void main(String[] args) {
    Container<Integer> intBox = new Container<>();
    intBox.setContent(123);
    System.out.println("Integer value: " + intBox.getContent());

    Container<String> strBox = new Container<>();
    strBox.setContent("Hello World");
    System.out.println("String value: " + strBox.getContent());
  }
}

Benefits of Advanced Generics