Monday, April 18, 2011

Writing generic class in java

Consider the following class:

package com.vaani.generics.classes;

public class MyGenericClass<T>
{
    private T anyObject;
    
    public T getObject()
    {
        return anyObject;
    }
    
    public void setObject(T anyObject)
    {
        this.anyObject = anyObject;
    }
    
    public String toString()
    {
        return anyObject.toString();
    }
}

Note the following syntax :
public class MyGenericClass<T>
The above statement essentially says that we wish to make the MyGenericClass class as a Generic Class. Technically, it is now a parametric class and T is called a type parameter.

T serves as a place-holder for holding any type of Object. Note the usage of the type parameter within the class declaration. Now, the clients can use the above class by substituting any kind of object for the place-holder T.

public class MyGenericClassRunner
{
    public static void main(String[] args) throws Exception
    {
        MyGenericClass<String> stringHolder = 
            new MyGenericClass<String>();
        stringHolder.setObject(new String("String"));
        System.out.println(stringHolder.toString());
        
        MyGenericClass<URL> urlHolder = new MyGenericClass<URL>();
        urlHolder.setObject(new URL("http://www.k2java.blogspot.com"));
        System.out.println(urlHolder.toString());
    }
}

Though parameter is placeholder, its much different from templates in c++.

Note how the clients or users of this class instantiates an instance for the MyGenericClass class. 
MyGenericClass<String> stringHolder = 
            new MyGenericClass<String>();

This is called type substitution. For the type parameter O, the type String is substituted.

Generic classes having two or more parametric types

You can simply write:
public class My2ParameterClass<A, B>

So instead of 1 parameter have 2 parameters and initialize etc. like original.

No comments:

Post a Comment

Chitika