Topics Index

Generics - Java Example Program

class SampleGenericsDemo
    public static void main(String[] args)
        SampleGenerics<Integer> integerObject = new SampleGenerics<Integer>(45); // LINE A
        int integerValue = integerObject.getObject();
        System.out.println("Given Integer Value is : " +integerValue);
        SampleGenerics<String> stringObject;
        stringObject = new SampleGenerics<String>("MeritCampus"); // LINE B
        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 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.

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

© meritcampus 2019

All Rights Reserved.

Open In App