Thursday, 25 October 2012

Generic Return Types

Heres a method with a generic return type.

public <T>  T getValue(){
  return (T) new Integer(1);
}

< T > T means that the return type is generic. (T) will be used to cast the Integer to the type expected by the caller.
Number myNum = getValue();

Since myNum is of type Number, getValue() will return object of type of Number. This will only work if the original object is castable to the type caller expects. So you can go up and down your Type hierarchy or cast to an interface that the original object implements. In this case Integer extends Number so can  be casted to a Number

No comments:

Post a Comment