Menu
Topics Index
...
`

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>

Generics
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());
    }
}
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. SampleGenerics,and the other class is SampleGenericsDemo,which uses SampleGenerics. At LINE Awe create an object for Integer and at LINE Bwe create one more object for String. By using the objects we invoke the methods of SampleGenerics class.

THINGS TO TRY
  • Create One more object for Double in SampleGenericsDemo and call the methods of SampleGenerics.class.

Edit | Back

© meritcampus 2016 - 2017

All Rights Reserved.