Java-Generic Constructors

Generic Constructors

It is possible for constructors to be generic, even if their class is not. For example, in the following program, NumberToInt constructor specifies a parameter of a generic type, which must be a subclass of Number, NumberToInt constructor can be called with any numeric type, including Integer, Float, or Double. Therefore, even though NumberToInt is not a generic class, its constructor is generic. Notice that NumberToInt constructor calls look like normal constructor calls. Generic constructor also infer its type from its  arguments.

Program

Generic Constructors


Program Source

class NumberToInt {

     <T extends Number> NumberToInt(T t) {

        int x = t.intValue();
        System.out.println("T -> "+t.getClass().getName());
        System.out.println("Int x = " + x);
    }
}

public class Javaapp {

    public static void main(String[] args) {

        NumberToInt fti = new NumberToInt(45.67f);
        NumberToInt dti = new NumberToInt(67.67d);
    }
}

Leave a Comment