A generic class has the facility to declare more than one type parameter. To specify two or more type parameters, simply use a comma - seperated list.
The following program explains how a generic class works with two type parameters.
class GenericsDemo
{
public static void main(String args[])
{
TwoGenerics<Integer, String> obj = new TwoGenerics<Integer, String>(45, "Meritcampus"); // LINE A
obj.showTypes();
int integerValue = obj.getOb1();
System.out.println("The given Integer is : " + integerValue);
String str = obj.getOb2();
System.out.println("The given String is : " + str);
}
}
class TwoGenerics<T, V>
{
T ob1;
V ob2;
TwoGenerics(T ob1, V ob2)
{
this.ob1 =ob1;
this.ob2 =ob2;
}
T getOb1()
{
return ob1;
}
V getOb2()
{
return ob2;
}
void showTypes()
{
System.out.println("Type of T is : " + ob1.getClass().getName());
System.out.println("Type of V is : " + ob2.getClass().getName());
}
}
OUTPUTType of T is : java.lang.Integer
Type of V is : java.lang.String
The given Integer is : 45
The given String is : Meritcampus
DESCRIPTIONAt LINE A
we created an instance for TwoGenerics.
In this case, Integer
is substituted for T,
and String
is substituted for V.
THINGS TO TRY
- Create a generic class with three type parameters.