CODE
class SampleGenericsDemo
{
public static void main(String[] args)
{
SampleGenerics<Integer> integerObject = new SampleGenerics<Integer>(45); // LINE A
integerObject.showType();
int integerValue = integerObject.getObject();
System.out.println("Given Integer Value is : " +integerValue);
SampleGenerics<String> stringObject;
stringObject = new SampleGenerics<String>("MeritCampus"); // LINE B
stringObject.showType();
String str = stringObject.getObject();
System.out.println("Given String is : " +str);
}
}
class SampleGenerics<T> {
T object;
SampleGenerics(T object)
{
this.object = object;
}
public T getObject() {
return object;
}
void showType()
{
System.out.println("Type of T is : " + object.getClass().getName());
}
}
Type of T is : java.lang.Integer
Given Integer Value is : 45
Type of T is : java.lang.String
Given String is : MeritCampus
In this program contains two classes. One class is generic class i.e. SampleGenerics,
and the other class is SampleGenericsDemo,
which uses SampleGenerics
. At LINE A
we create an object for Integer
and at LINE B
we create one more object for String
. By using the objects we invoke the methods of SampleGenerics
class.
Double
in SampleGenericsDemo
and call the methods of SampleGenerics.
class.