Generic is one of the useful language feature introduced from Java 5.0. There are many great features as part of the Generics is not fully utilized by the programmers. One such instance is the use of generic constructors. This example shows how to use the generic with constructor and takes the different type arguments.
In the below example, I have used the generic type T extends Number for constructor definition and also used “T” as the constructor argument. Here while invoking the constructor, any subclass can be passed to the argument which will be acceptable by that constructor.
Lets look at the simple example which extends the Number class and takes its sub classes Integer, Float, Double and Long as the arguments.
GenericExample.java
package javabeat.net.core; /** * Generic Constructor Example * * @author Krishna * */ public class GenericExample { <T extends Number> GenericExample(T value) { if (value instanceof Integer){ System.out.println("Integer Value : " + value); } if (value instanceof Float){ System.out.println("Float Value : " + value); } if (value instanceof Double){ System.out.println("Double Value : " + value); } if (value instanceof Long){ System.out.println("Long Value : " + value); } } public static void main(String[] args) { //Invoke with integer value GenericExample example = new GenericExample(12); //Invoke with float value example = new GenericExample(12.0F); //Invoke with double value example = new GenericExample(12.0); //Invoke with long value example = new GenericExample(12L); } }
Output…
Integer Value : 12 Float Value : 12.0 Double Value : 12.0 Long Value : 12