Topics Index

Generics >
Siva Nookala - 14 Apr 2016
Generics are given the ability to create generalized classes, interfaces and methods by operating through references of type Object. It provides compile-time type safety that allows programmers to catch invalid types at compile time and also expand ability to reuse code.

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.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App