| 5 | import java.util.Objects; |
| 6 | |
| 7 | public class Holder<T> { |
| 8 | private T value; |
| 9 | public Holder() {} |
| 10 | public Holder(T val) { value = val; } |
| 11 | public void set(T val) { value = val; } |
| 12 | public T get() { return value; } |
| 13 | @Override public boolean equals(Object o) { |
| 14 | return o instanceof Holder && |
| 15 | Objects.equals(value, ((Holder)o).value); |
| 16 | } |
| 17 | @Override public int hashCode() { |
| 18 | return Objects.hashCode(value); |
| 19 | } |
| 20 | public static void main(String[] args) { |
| 21 | Holder<Apple> apple = new Holder<>(new Apple()); |
| 22 | Apple d = apple.get(); |
| 23 | apple.set(d); |
| 24 | // Holder<Fruit> Fruit = apple; // Cannot upcast |
| 25 | Holder<? extends Fruit> fruit = apple; // OK |
| 26 | Fruit p = fruit.get(); |
| 27 | d = (Apple)fruit.get(); // Returns 'Object' |
| 28 | try { |
| 29 | Orange c = (Orange)fruit.get(); // No warning |
| 30 | } catch(Exception e) { System.out.println(e); } |
| 31 | // fruit.set(new Apple()); // Cannot call set() |
| 32 | // fruit.set(new Fruit()); // Cannot call set() |
| 33 | System.out.println(fruit.equals(d)); // OK |
| 34 | } |
| 35 | } |
| 36 | /* Output: |
| 37 | java.lang.ClassCastException: Apple cannot be cast to |
| 38 | Orange |
nothing calls this directly
no outgoing calls
no test coverage detected