Parameterized Generic class and method in Java
Writing Generic parametrized classes and methods in Java is easy and should be used as much as possible. Generic in Java was introduced in version 1.5 along with Autoboxing, Enum, varargs and static import. Most of the new code development in Java uses type-safe Generic collection i.e. HashSet in place of HashSet but still Generic is underused in terms of writing its own parametrized classes and method. I agree that most Java programmers have started using Generic while working with the Java collection framework but they are still not sure how Generic can allow you to write Template kind of classes which can work with any Type just like the parametrized ArrayList in Java which can store any type of element.
In the last couple of articles about Generic, we have seen How Generic works in Java and explored wild cards of Generic in Java and In this part of the Java Generic example we will see How to write parametrized Generic Class and method in Java.
In the last couple of articles about Generic, we have seen How Generic works in Java and explored wild cards of Generic in Java and In this part of the Java Generic example we will see How to write parametrized Generic Class and method in Java.
In this Generic tutorial, we will write a parameterized class called Wrapper which can contain any type specified while creating an instance just like any collection e.g. Hashtable in Java.
This generic class will contain two parametrized methods T getItem () and setItem(T) whose Type will be determined at the time of instantiation.
We will also see the old version of the same class which is written without using Generic to demonstrate concrete benefit offered by Generic type-safety in terms of coding and development.
We will also see the old version of the same class which is written without using Generic to demonstrate concrete benefit offered by Generic type-safety in terms of coding and development.
Guideline of writing parameterized Generic class
1) Use type parameter in Class declaration e.g. class Wrapper where T is a generic type parameter stands for Type, you can also use which stands for Element and much suitable for collection kind of data structure which stores elements.
2) Now use this T in all places where you need to use actual Type e.g. While declaring the method argument while writing return type of method etc.
/**
* Java program to demonstrate How to write a parameterized classes in Java and type-safety
* provided by the parameterized class. The program also compares non parameterized to
* Java program to demonstrate How to write a parameterized classes in Java and type-safety
* provided by the parameterized class. The program also compares non parameterized to
* parameterized class to highlight issues with non-generic classes in Java.
*
* @author Javin Paul
*/
public class GenericTest {
public static void main(String args[]) {
*
* @author Javin Paul
*/
public class GenericTest {
public static void main(String args[]) {
//string wrapper
Wrapper<String> stringWrapper = new Wrapper<String>();
stringWrapper.setItem("Test");
System.out.println(stringWrapper.getItem());
//compilation error, type checking at compile time
//stringWrapper.setItem(new StringBuffer(""));
Wrapper<Integer> integerWrapper = new Wrapper<Integer>();
integerWrapper.setItem(123);
//compilation error, type safety checking
//integerWrapper.setItem("123");
System.out.println(integerWrapper.getItem());
// Now let's see how to write generic wrapper without using
// JDK1.5 generic and what problem it poses
OldWrapper oldStringWrapper = new OldWrapper();
//no compilation error i.e. no type checking at compile time
oldStringWrapper.setItem(123);
//will throw ClassCastException at runtime
((String)oldStringWrapper.getItem()).toUpperCase();
}
}
/*
* wrapper can wrap any item
* Generic parameterized form of Wrapper, offers compile time type checking
*/
class Wrapper<T> {
private T item;
public T getItem(){
return item;
}
public void setItem(T item){
this.item = item;
}
}
/*
* Object form of Wrapper fragile and error prone
*/
class OldWrapper{
private Object item;
public Object getItem(){
return item;
}
public void setItem(Object item){
this.item = item;
}
}
Wrapper<String> stringWrapper = new Wrapper<String>();
stringWrapper.setItem("Test");
System.out.println(stringWrapper.getItem());
//compilation error, type checking at compile time
//stringWrapper.setItem(new StringBuffer(""));
Wrapper<Integer> integerWrapper = new Wrapper<Integer>();
integerWrapper.setItem(123);
//compilation error, type safety checking
//integerWrapper.setItem("123");
System.out.println(integerWrapper.getItem());
// Now let's see how to write generic wrapper without using
// JDK1.5 generic and what problem it poses
OldWrapper oldStringWrapper = new OldWrapper();
//no compilation error i.e. no type checking at compile time
oldStringWrapper.setItem(123);
//will throw ClassCastException at runtime
((String)oldStringWrapper.getItem()).toUpperCase();
}
}
/*
* wrapper can wrap any item
* Generic parameterized form of Wrapper, offers compile time type checking
*/
class Wrapper<T> {
private T item;
public T getItem(){
return item;
}
public void setItem(T item){
this.item = item;
}
}
/*
* Object form of Wrapper fragile and error prone
*/
class OldWrapper{
private Object item;
public Object getItem(){
return item;
}
public void setItem(Object item){
this.item = item;
}
}
If you look at the above example and compare both parameterized versions of class and non parameterized or raw versions of the same class, You can derive two substantial benefits of using generic parameterized class and method :
1) Parameterized classes offer compile-time type verification. Which is not present in non Generic or non-parametrized version of the class.
2) If you use a Generic parametrized method or class you don't need to cast into a specific type
3) Generic methods don't throw ClassCastException as Type verification was already done at compile time.
How to write parameterized method in Java Generics:
What is parameterized method in Java? This is a popular Java Generics interview question and followed by questions like how to write parameterized method using Generics. Parameterized methods in Java are those method writing using the Generics feature of Java which accepts method argument as type and/or return type instead of any particular type like String, Double, or Float.
The parameterized method prevents duplication of code and provides type-safety at compile time. Any static utility method which operates on Object type is a good candidate for making parameterized or Generic methods in Java.
Here is a code example of How to write a Generic Parameterized method in Java:
The parameterized method prevents duplication of code and provides type-safety at compile time. Any static utility method which operates on Object type is a good candidate for making parameterized or Generic methods in Java.
Here is a code example of How to write a Generic Parameterized method in Java:
/**
* Java program to demonstrate how to write parameterized method in Java
* parameterized method needs a type parameter declaration before return
* type, here is a type parameter
* @author Javin
*/
class ItemUtils{
public static <T> T wrap(T item){
//code for wrapping item
return item;
}
}
* Java program to demonstrate how to write parameterized method in Java
* parameterized method needs a type parameter declaration before return
* type, here
* @author Javin
*/
class ItemUtils{
public static <T> T wrap(T item){
//code for wrapping item
return item;
}
}
In Summary, use the Generic parameterized version of class and method in place of using Object as a generic type. If you have a code that is on Java 5 and doesn’t use Generic, consider refactoring that code to use Generic to enjoy benefits provided by Generics like type-safety, no ClassCastException, and no need of casting.
That's all on this Java Generic Example of how to create parameterized class and method using Generic. Just remember that Generic is only available from Java 1.5 onwards and you can not write parameterized class and method in Java 1.4 or lower version.
Other advanced Java tutorial from Javarevisited Blog:
2 comments :
The oldWrapper class problem can be overridden by simply avoiding to convert to a string, such as writing to the console:
//will throw ClassCastException at runtime L.36-37 System.out.println(oldStringWrapper.getItem());
Can you provide examples of problems that can be resolved using generics as illustrated above?
Hi Jon,
Main problem Geneirc solves is type-safety, It prevents you adding incorrect type during compile time, which automatically reduce amount of casting you do and removes risk of ClassCastException.
Post a Comment