Wednesday, February 6, 2008

Part 3 of 4: GENERICS in JAVA

How polymorphism works in Generic?

Lets start with a basic analogy between collection and array. Both are more or less similar in the sense that we can use both to hold objects.

Polymorphism in Array and related problems:
In arrays following statement is perfectly valid-
Number[] obj = new Integer[5];

How this statement is interpreted by JAVA Complier and Java Executor?
Java Compiler:
obj will refer to a "Number" object and Object itself can refer to 5 "Number" Object or "subclasses of Number" Objects.

Continuing the compiler behavior, below statements compile fine:
obj[1]= new Intger(123);
obj[2]= new Double(123);

As Both Double and Integer are subclasses of Number.

Java Executor:
After executing this statement one "Number" object will created onto HEAP memory and object itself can refer to 5 "Integer" Objects.But as compiler has allowed to store a "Double" object, at Runtime - Java Executor will throw "ArrayStoreException".so Executor has to suffer because of COMPILER stupidity.

THIS IS THE SITUATION WHICH THE SUN ENGINEERS ARE TRYING TO AVOID IN GENERICS. So THEY are trying to improve COMPILER to DETECT this kind of problems in GENERICS.

Polymorphism in GENERICS:

If we try this-
ArrayList< Object > store_room = new ArrayList< String >( );

COMPILER WILL NOT ALLOWED THIS.

Correct expression is -
ArrayList< String > store_room = new ArrayList< String >( );

As it is clear that all this is because JAVA wants to AVOID EXCEPTION in STORING the objects in STORE ROOM (COLLECTION).

How we create STORE ROOM (COLLECTION OBJ) has been given the liberty, which means-

List< String > store_room = new ArrayList< String >( );


So POLYMORPHISM is ALLOWED While creating a STORE ROOM ( COLLECTION ), but POLYMORPHISM is NOT ALLOWED while storing the objects in STORE ROOM.

Refer to the line above:
"THIS IS THE SITUATION WHICH THE SUN ENGINEERS ARE TRYING TO AVOID IN GENERICS. So THEY are trying to improve COMPILER to DETECT this kind of problems in GENERICS."

so its COMPILER which checks that there is no polymorphism when it comes to STORING of DATA in GENERICS.

JAVA COMPILER:

List< Object> store_room = new ArrayList< String >( );

Result : Compilation error, I am trying to avoid Object storing exceptions.

List< String > store_room = new ArrayList< String >( );

Result: OK, but as now JAVA Executor doesn't need to worry about Object storing, I should remove the unncessary things. So after compilation-

List< String > store_room = new ArrayList< String >( ) -->
                                                                                     List store_room = new ArrayList( );

This is called as TYPE ERASURE.GENERICS ARE FOR COMPILE TIME ONLY. Thats why it makes a strict check at the compile time.