Saturday, August 18, 2012

How to write parametrized Generic class and method in Java Example

Parameterized Generic class and method in Java
Writing Generic parametrized class and method 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 own parametrized classes and method. I agree that most Java programmers has 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 article  about Generics we have seen How Generic works in Java and  explored wild cards of Generic in Java and In this part of Java Generic example we will see How to write parametrized Generic Class and method in Java.


How to write parametrized class and method in Java - Example tutorialIn this Generic tutorial we will write a parameterized class called Wrapper which can contain any Type specified while creating instance just like any collection e.g. Hashtable in Java. This generic class will contain two parametrized method 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.

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 parameterized class in Java and type-safety
 * provided by parameterized class. Program also compares non parameterized to
 * parameterized class to highlight issue with non generic classes in Java.
 *
 * @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;
   
}
}


If you look at above example and compare both parameterized versions of class and non parameterized or raw version of 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 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? is a popular Java Generics interview question and followed by question like how to write parameterized method using Generics.  Parameterized method in Java are those method writing using Generics feature of Java which accept method argument as type and/or return type instead of any particular type like String, Double or Float. Parameterized method prevents duplication of code and provides type-safety at compile time. Any static utility method which operate on Object type is good candidate of making parameterized or Generic method in Java. Here is a code example of How to write 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;
    }
   
}

In Summary use Generic parameterized version of class and method in place of using Object as generic type. If you have a code which 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 :

Jon said...

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?

Javin @ ArrayList vs LinkedList said...

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