Created
May 11, 2012 20:40
-
-
Save iande/2662278 to your computer and use it in GitHub Desktop.
Bounded Type Parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The bounded type parameter dictates the kinds of Box instances we can create. | |
public class NumberBox<T extends Number> { | |
private T _number; | |
public NumberBox() { this(null); } | |
public NumberBox(T toStore) { | |
set(toStore); | |
} | |
public T get() { return _number; } | |
public void set(T val) { _number = val; } | |
} | |
// The following are valid: | |
NumberBox<Integer> intBox = new NumberBox<Integer>(); | |
NumberBox<Float> fltBox = new NumberBox<Float>(); | |
NumberBox<Double> dblBox = new NumberBox<Double>(); | |
NumberBox<Number> numBox = new NumberBox<Number>(); | |
// The following are invalid: | |
NumberBox<String> strBox = new NumberBox<String>(); | |
NumberBox<Object> objBox = new NumberBox<Object>(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Now, we deal with wildcards | |
public class WildcardExample { | |
public static void showValuesBad(NumberBox<Number> box) { | |
System.out.println(box.get().doubleValue()); | |
System.out.println(box.get().intValue()); | |
} | |
public static void showValuesGood(NumberBox<? extends Number> box) { | |
System.out.println(box.get().doubleValue()); | |
System.out.println(box.get().intValue()); | |
} | |
public static void putValuesBad(NumberBox<? extends Number> box) { | |
box.set(new Integer(42)); | |
} | |
public static void main(String[] args) { | |
NumberBox<Integer> intBox = new NumberBox<Integer>(new Integer(4)); | |
NumberBox<Double> dblBox = new NumberBox<Double>(new Double(3.2)); | |
// should be invalid: | |
showValuesBad(intBox); | |
showValuesBad(dblBox); | |
// should be valid: | |
showValuesGood(intBox); | |
showValuesGood(dblBox); | |
// should be invalid: | |
putValuesBad(intBox); | |
putValuesBad(dblBox); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment