6/08/2008

Java generics examples -- parameterized class

Not only can Java generics be used in fields and methods, it can also be used in class definitions to produce parameterized classes. Since JDK 1.5, many built-in Java classes have been retrofitted to parameterized forms. An example is java.lang.Class, which is declared to be public final class Class<T>, the parameter type <T> represents the actual type modeled by this Class object. One benefit is that some of its methods can take or return specific types, avoiding casting while enforcing type-check.

It's also easy to write your own parameterized class. The following is a Member class whose Id field can be parameterized to String, Integer, etc:

package javahowto;
public class Member<T> {
private T id;
public Member(T id) {
this.id = id;
}
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
public static void main(String[] args) {
Member<String> mString = new Member<String>("id1");
mString.setId("id2");
System.out.printf("id after setting id: %s%n", mString.getId());
//output: id after setting id: id2

Member<Integer> mInteger = new Member<Integer>(1);
mInteger.setId(2);
System.out.printf("id after setting id: %d%n", mInteger.getId());
//output: id after setting id: 2
}

8 comments:

Sogy said...

Wow was looking for exactly this. thanks a lot. Its a good example and clean and simple explanation.

Anonymous said...

Yes, good and understandable.

Anonymous said...

So what if I want to treat T as another parametrized class and define a field T field=new T(); //or even without the new

Anonymous said...

very nice...
explained with simple example

Anonymous said...

Since my college day, Template is like mystery. But through this example, it's just cake for me now. :)
Thanks a Lot.

Anonymous said...

Thanks a lot!

Anonymous said...

Thanks

Anand Devaraj said...

Good one