Monday, 3 March 2014

Key note on Java Generics

1. While you may safely assign a generic type object to a raw type, the converse is not true.
e.g. : Box <Integer> b = new Box <Integer> (); //Generic type
Box newBox = b;

This is legal. As for the converse, Box newBox = new Box ();// raw type
b = newBox;

The above doesn't result in a compile-time error but leads to a compile-time warning. Note that raw types bypass generic type checks at compile-time.

2. When using bounded generic type parameters, note that you may invoke method of the class being extended.

e.g. :
public class Box <T extends Integer>  {
     
       public T getDouble (T t) {
              return t.intValue() * 2;
       }
}
This is to note that the application of intValue() as shown in the preceding example is legal.

3. From 1, we can see that it is perfectly legal to cast an Integer to an Object. This is by virtue of their super type - sub type relationship or "isa" relationship as it is sometimes called. This does somehow lead to a common misconception which is shown below:

public void someMethod ( Box <Number> boxN ) {
/*do something */
}

Now, the parameter boxN here accepts any Box <Number> object. It must be noted though that boxN cannot accept objects of Box <Integer> types even if Integer extends Number. This is because Box <Integer> is not a subtype of Box <Number> and this is true even if Integer itself is a subclass of Number.





No comments:

Post a Comment