How generics improves type safety?

We can create ageneralized class, interface or method of type Object.
Because Object is the super class of any other classes, an Object reference can refer to any type of object. This is same as generics.
But it can not provide type safety. So we have to explicitely type cast to translate between Object and the type of data is actually being operated upon. But with generics all the casts are automatic and implicit.
Example:(non generic code)
class Gen
{
Object obj;
Gen(Object a){this.obj=a;}
Object getobj(){return obj;}
};
class demo
{
public static void main(String[] args){
Gen i=new Gen(10);
int x=(Integer)i.getobj();//manual type cast
Gen str=new Gen("bhabani");
String y=(String)str.getobj();//manual type cast
i=str;
x=(Integer)i.getobj();
System.out.println(x);
}};
This above code prevents java compiler from having any knowledge about the type os data actually stored in Gen, which is bad for two reasons

1-Explicit casts needed to retrieve the stored data.
2-Many kinds of type mismatch errors can not be found until runtime.
If we will not do the explicit type cast then it will be compilation error(incompatible type). but in case of generics we do not need this.
Again see the last three lines of the above program. Here ‘str’ is assigned to ‘i’. However ‘str’ refers to an Object which contains String not an Integer. The assignment is syntactically correct because both have ‘Gen’ class reference. Without generics java compiler has no way to notice this. As a result compilation is success but it through run time Exception(As String is casted to Integer).
In the below program we need not manually type cast to the required type. Because the compiler knows which type of data is stored in Gen.
class Gen
{
T obj;
Gen(T a){this.obj=a;}
T getobj(){return obj;}
};
class demo
{
public static void main(String[] args){
Gen i=new Gen(10);
int x=i.getobj();
Gen str=new Gen("bhabani");
String y=str.getobj();
}};

No comments:

Post a Comment