Menu
Topics Index
...
`


Generics > A Simple Generics Example >
Siva Nookala - 03 Mar 2017
The functionality of generic SampleGenerics shown in the previous program A Simple Generics Example is the same functionality found without generics, by simply specifying Object as the data type and employing the proper casts, since Object is the super class to all classes.
Advantages Of Generic Class
  • Type safe
  • Converting run time errors into compile time errors

The following program illustrate the benifits of generics :
How Generics Improve Type Safety
class SampleNonGenericDemo
{
    public static void main(String args[])    
    {
        SampleNonGeneric integerObject = new SampleNonGeneric(12);
        
        integerObject.displayType();
        
        Integer integerValue = (Integer)integerObject.getObj(); // LINE A
        
        System.out.println("The integer value is : "+integerValue);
        
        SampleNonGeneric stringObject;
        
        stringObject = new SampleNonGeneric("MeritCampus");
        
        stringObject.displayType();
        
        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());
    }
}
OUTPUT

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

DESCRIPTION

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.

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

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App