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); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter