Online Hibernate Training just in Rs. 1000

One week online training in Hibernate ORM framework. Learn Hibernate Framework and enhance your skills. Best Online Hibernate training at 90% discount. Join Now!! Offer is valid Only for limited Period!!! Online Training

Generic Classes

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

Ads

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

Share on Google+Share on Google+

Generic Classes

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

Advertisements

 

Discuss: Generic Classes  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:2
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

Ads

 

Ads