Name: Generics
Class name: SampleGenericsDemo
Class content: 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); }
Include main method: false
Output: Type of T is : java.lang.Integer Given Integer Value is : 45 Type of T is : java.lang.String Given String is : MeritCampus
Description: In this program contains two classes. One class is generic class i.e. <cw>SampleGenerics, </cw>and the other class is <cw>SampleGenericsDemo, </cw>which uses <cw>SampleGenerics</cw>. At <cw>LINE A </cw>we create an object for <cw>Integer</cw> and at <cw>LINE B </cw>we create one more object for <cw> String</cw>. By using the objects we invoke the methods of <cw>SampleGenerics</cw> class.
Things to try: <bullet>Create One more object for <cw>Double</cw> in <cw>SampleGenericsDemo</cw> and call the methods of <cw>SampleGenerics. </cw>class.</bullet>
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.