Java-Generic with Multiple Parameters

Generic with Multiple Parameters

You can declare more than one type parameter in a generic type. To specify two or more type parameters, simply use a comma-separated list. For example, in the following program, TwoGenClass specifies two type parameters : T and V, separated by comma, Because it has two type parameters, two type arguments must be passed to TwoGenClass when an object is created, as :

In this case, Integer is substituted for T, and String is substituted for V.

Program

final

Program Source

class GenClass<T, V> {
    
    T tob;
    V vob;
    
    GenClass(T to, V vo)
    {
        tob = to;
        vob = vo;
    }
    
    T getFirstObj()
    {
        return tob;
    }
    
    V getSecondObj()
    {
        return vob;
    }
    
    void showTypes()
    {
        System.out.println("T Type : "+tob.getClass().getName());
        System.out.println("V Type : "+vob.getClass().getName());
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        GenClass<Integer, String> iob = new GenClass<Integer, String>(20,"Twenty");
        iob.showTypes();
        int getInt = iob.getFirstObj();
        String getStr = iob.getSecondObj();
        System.out.println("Int Value : "+getInt);
        System.out.println("Str Value : "+getStr);
    }
}

Leave a Comment