How to create a constructor using generic types in Java

1 Answer

0 votes
class GenericConstructorExample {
    private double value;

    // Generic constructor
    public <T extends Number> GenericConstructorExample(T input) {
        this.value = input.doubleValue();
        System.out.println("Constructor received: " + input);
    }

    public void show() {
        System.out.println("Stored value: " + value);
    }
}

public class Main {
    public static void main(String[] args) {
        GenericConstructorExample a = new GenericConstructorExample(42);       // int
        GenericConstructorExample b = new GenericConstructorExample(3.14);     // double
        GenericConstructorExample c = new GenericConstructorExample(7.5f);     // float

        a.show();
        b.show();
        c.show();
    }
}



/*
run:

Constructor received: 42
Constructor received: 3.14
Constructor received: 7.5
Stored value: 42.0
Stored value: 3.14
Stored value: 7.5

*/

 



answered 12 hours ago by avibootz
...