Home Help Java G Generic Classes



Generic Classes
Posted on: July 27, 2011 at 12:00 AM
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
.get());
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 

 

Related Tags for Generic Classes:


More Tutorials from this section

Ask Questions?    Discuss: Generic Classes  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.