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
}

12 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

Anonymous said...

I actually understood this one.

Steve Smith said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India

ERP said...

ERPTREE is a leading oracle fuison HCM Training Institute. we offer this course through online we have great experience in succeeding students through online courses. we can calculate our performance through their honest comments in our sites in supporting our services. we have referral program so candidates can earn money through referral. you can share your live experience with other can generate you some money.

for more information please click billow link

Oracle Fusion HCM Training

Vũ Diệu Linh said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000