Wednesday, 22 August 2012

How to write parametrized class and method in Java – Generics Example


Parametrized 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 parametrized 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 parametrized 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 parametrized class in Java and type-safety
 * provided by parametrized class. Program also compares non parametrized to
 * parametrized 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 parametrized 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 parametrized versions of class and non parametrized or raw version of same class,  You can derive two substantial benefits of using generic parametrized class and method :

1) Parametrized 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 parametrized method in Java Generics:
What is parametrized method in Java? is a popular Java Generics interview question and followed by question like how to write parametrized method using Generics.  Parametrized 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 StringDouble or Float. Parametrized 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 parametrized or Generic method in Java. Here is a code example of How to write Generic Parametrized method in Java:

/**
 * Java program to demonstrate how to write parametrized method in Java
 * parametrized 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 parametrized 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 parametrized class and method using Generic. Just remember that Generic is only available from Java 1.5 onwards and you can not write parametrized class and method in Java 1.4 or lower version.

No comments:

Post a Comment