wildcards
Fri Jun 07 2024 12:02:16 GMT+0000 (Coordinated Universal Time)
Saved by
@dbms
public class MagicBox<T> {
private T item;
public void addItem(T item) {
this.item = item;
System.out.println("Added item to the magic box: " + item);
}
public T getItem() {
return item;
}
public void processBox(MagicBox<? super Integer> box) {
System.out.println("Items in the box are processed [" + box.getItem() + "]");
}
public static void main(String[] args) {
MagicBox<Integer> integerBox = new MagicBox<>();
integerBox.addItem(43);
MagicBox<String> stringBox = new MagicBox<>();
stringBox.addItem("Sofiya");
MagicBox<Boolean> booleanBox = new MagicBox<>();
booleanBox.addItem(false);
MagicBox<Object> objectBox = new MagicBox<>();
objectBox.addItem(43.43);
// Using processBox with a MagicBox that can accept Integer or its supertypes
integerBox.processBox(integerBox);
integerBox.processBox(objectBox);
// The following lines will cause compilation errors as they don't match the processBox parameter type
// integerBox.processBox(stringBox);
// integerBox.processBox(booleanBox);
}
}
content_copyCOPY
Comments