Interview question
What are bounded type parameters in Java Generics? Java Generics में bounded type parameters क्या हैं?
Answer
Bounded type parameters restrict what types can be used, using 'extends' to require the type to be a subtype of a specific class or interface (or implement it, for interfaces).
// Upper bound - T must be Number or a subclass of Number
class Calculator<T extends Number> {
private T value;
public Calculator(T value) { this.value = value; }
public double square() {
return value.doubleValue() * value.doubleValue(); // Number's method available
}
}
Calculator<Integer> intCalc = new Calculator<>(5);
System.out.println(intCalc.square()); // 25.0
// Calculator<String> stringCalc = new Calculator<>('x'); // COMPILE ERROR
// String is not a subtype of Number
// Multiple bounds - class first, then interfaces, separated by &
interface Printable {
void print();
}
class Item implements Comparable<Item>, Printable {
public int compareTo(Item o) { return 0; }
public void print() { System.out.println('Item'); }
}
class Container<T extends Comparable<T> & Printable> {
private T item;
public Container(T item) { this.item = item; }
public void show() {
item.print(); // available from Printable
item.compareTo(item); // available from Comparable
}
}
// Generic method with a bounded type parameter
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
System.out.println(max(10, 20)); // 20 - works for any Comparable typeBounded type parameters यह restrict करते हैं कि कौन-से types इस्तेमाल हो सकते हैं, 'extends' से type को किसी specific class/interface का subtype होना ज़रूरी बताते हैं।
// Upper bound - T Number या उसका subclass होना चाहिए
class Calculator<T extends Number> {
private T value;
public Calculator(T value) { this.value = value; }
public double square() {
return value.doubleValue() * value.doubleValue();
}
}
Calculator<Integer> intCalc = new Calculator<>(5);
System.out.println(intCalc.square()); // 25.0
// Calculator<String> stringCalc = new Calculator<>('x'); // COMPILE ERROR
// Multiple bounds - class पहले, फिर interfaces, & से अलग
interface Printable {
void print();
}
class Item implements Comparable<Item>, Printable {
public int compareTo(Item o) { return 0; }
public void print() { System.out.println('Item'); }
}
class Container<T extends Comparable<T> & Printable> {
private T item;
public Container(T item) { this.item = item; }
public void show() {
item.print();
item.compareTo(item);
}
}
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
System.out.println(max(10, 20)); // 20Was this answer clear?