Topics Index

How Generics Improve Type Safety - Java Example Program

How Generics Improve Type Safety
class SampleNonGenericDemo
    public static void main(String args[])    
        SampleNonGeneric integerObject = new SampleNonGeneric(12);
        Integer integerValue = (Integer)integerObject.getObj(); // LINE A
        System.out.println("The integer value is : "+integerValue);
        SampleNonGeneric stringObject;
        stringObject = new SampleNonGeneric("MeritCampus");
        String string = (String)stringObject.getObj();           // LINE B
        System.out.println("The given string is :"+string);
        integerObject = stringObject; // LINE C
        // integerValue = (Integer)integerObject.getObj(); //  LINE D

class SampleNonGeneric
    Object obj;
    public SampleNonGeneric(Object obj)
        this.obj = obj;
    Object getObj()
        return obj;
    void displayType()
        System.out.println("The type of object is : "+obj.getClass().getName());

The type of object is : java.lang.Integer
The integer value is : 12
The type of object is : java.lang.String
The given string is : MeritCampus


Here SampleNonGeneric replaces all uses of T With Object. We observed explicit casts must be needed to retrieve the stored data at LINE A and LINE B. AtLINE C stringObjectis assigned to integerObject.It compiles but is conceptually wrong. At LINE D we try to get the Integer value then run time error occurs. Here the problem is now integerObjectrefers to an objectthat stores a Stringnot an Integer.This is the dangerous situation.

  • Uncomment the line at LINE Dand try to run the program. It gives run time exception.

© meritcampus 2019

All Rights Reserved.

Open In App