Create Generic Constructor in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class GenericConstructor { private double value; <T extends Number> GenericConstructor(T arg) { value = arg.doubleValue(); } void showValue() { System.out.println("value: " + value); } } public class GenericConstructorTest { public static void main(String args[]) { GenericConstructor gc1 = new GenericConstructor(100); GenericConstructor gc2 = new GenericConstructor(123.5F); gc1.showValue(); gc2.showValue(); } } |
Output:
value: 100.0
value: 123.5
value: 123.5