Menu
Topics Index
...
`


Generics >
Siva Nookala - 07 Apr 2016
A generic class has the facility to declare more than one type parameter. To specify two or more type parameters, simply use a comma - seperated list.

The following program explains how a generic class works with two type parameters.
Print Types
class GenericsDemo
{
    public static void main(String args[])
    {
        
        TwoGenerics<Integer, String> obj = new TwoGenerics<Integer, String>(45, "Meritcampus"); // LINE A
        
        obj.showTypes();
        
        int integerValue = obj.getOb1();
        
        System.out.println("The given Integer is : " + integerValue);
        
        String str = obj.getOb2();
        
        System.out.println("The given String is : " + str);
    }
}

class TwoGenerics<T, V>
{
    T ob1;

    V ob2;
        
    TwoGenerics(T ob1, V ob2)
    {

        this.ob1 =ob1;
    
        this.ob2 =ob2;
    
    }
        
    T getOb1()
    {
        return ob1;
    }
        
    V getOb2()
    {
        return ob2;
    }
    void showTypes()
    {
        System.out.println("Type of T is : " + ob1.getClass().getName());
        System.out.println("Type of V is : " + ob2.getClass().getName());
    }
}
OUTPUT

Type of T is : java.lang.Integer
Type of V is : java.lang.String
The given Integer is : 45
The given String is : Meritcampus

DESCRIPTION

At LINE A we created an instance for TwoGenerics. In this case, Integer is substituted for T,and Stringis substituted for V.

THINGS TO TRY
  • Create a generic class with three type parameters.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.