Share on Google+Share on Google+

Generic Classes

In this section, you will learn to create Generic classes and how it can handle different types.

Generic Classes

In this section, you will learn to create Generic classes and how it can handle different types.

Generic Class declaration is similar to other non-Generic classes. There is only difference the name of the class is followed by a type parameter section(ex. <T>).

Similar to generic methods, the type parameter section can contains one or more type parameters separated by commas.

Since they accept parameters(at least one), that's whys they are known as parameterized types or parameterized classes.

Given below example will give you a clear idea :

public class GenericClassDemo<A> {
private A a;

public void set(A a) {
this.a = a;

public A get() {
return a;

public static void main(String[] args) {
GenericClassDemo<Integer> integerObj = new GenericClassDemo<Integer>();
GenericClassDemo<String> stringObj = new GenericClassDemo<String>();

integerObj.set(new Integer(30));
stringObj.set(new String("Roseindia"));

System.out.printf("Integer Type Object's Value :%d\n\n", integerObj
System.out.printf("String Type Object's Value :%s\n", stringObj.get());

Output :

Integer Type Object's Value :30

String Type Object's Value :Roseindia         

In the above example, you can see that when we create a integer type object of generic class, the variable A's type changed to Integer and also it changes the type of "set(A a)" method to "set(int a)". Similar things happens in the case of String type.

Download Source Code 




Posted on: July 27, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Generic Classes  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
November 12, 2011

what is the diffrene between normal class and genaric class.
January 12, 2012

in java why we are using this keyword