Home Help Java G Generic Classes
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Generic Classes

Advertisement
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 

 

Advertisements

Liked it!  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.

Posted on: July 27, 2011

Ask Questions?    Discuss: Generic Classes  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
M.prabhakar
November 12, 2011
j2se

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

in java why we are using this keyword
DMCA.com