Skip to main content

Java Generics III - Bounds and Wildcards

Posted by hellofadude on July 10, 2014 at 5:42 AM PDT

In part two of this series, I demonstrated the effect of erasure on type parameters within the body of a class. I used examples to show how type parameters were limited to accessing methods of the root Object class irrespective of the actual type with which it was replaced at a later time. I also demonstrated how to specify a bound with which one may constrain the type parameter so as to have access to methods other than those available to Object within the body of a class.

Here is another example code to emphasize the point; in this instance we have an oversimplified parameterised Converter class, whose type parameter is constrained to the Currency class and it's subtypes. The Converter class has only one method - convert() - that checks the equivalence of the name of the type parameter as returned by the getCurrency() method in another class, and returns a simple string on that basis. Here is the code:-

package generics.java.erasure;

abstract class Currency {
public String getCurrency() { return this.getClass().getSimpleName(); }
}
class Dollar extends Currency { }

public class Converter {
private T type;
static int GBP;
public Converter(T aType) { type = aType; }
public String convert(int amt) {
if(type.getCurrency().equals("Dollar"))
return "Value of $" + amt + " is " + "