Generic Constructor

Constructor can be generic even if class is not. For creating a generic constructor parameter type has to be specified before constructor name.


Syntax:


  <parameter-type-list>  class-name(constructor-arg-list)
   

Example :




class genericConstructor
{
<T> genericConstructor(T arg)
{
System.out.println(" Constructor with value:"+arg.toString());
}
}


class example
{
public static void main(String arg[])
{
// Creating object by passing int value which will be autoboxed into Integer Object
genericConstructor ob=new genericConstructor(102);

// Creating object by passing string value which will be autoboxed into String object
genericConstructor ob1=new genericConstructor("this");
}
}
/*Output:
Constructor with value:102
Constructor with value:this
*/

In above code one genericConstructor class having one generic constructor, means in constructor any type argument can be passed.

In main method one object is created by passing int data type value. When we passed 102 in constructor, then this is autoboxed into a Integer class object. That object is then passed to constructor. Second time we have passed String class object in constructor. So our constructor can take any type of single argument.