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
- 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());
}
}
OUTPUTThe 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
DESCRIPTIONHere 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
stringObject
is 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 integerObject
refers to an object
that stores a String
not an Integer
.This is the dangerous situation.
THINGS TO TRY
- Uncomment the line at
LINE D
and try to run the program. It gives run time exception.