Home | | Web Programming | A Generic Class with Two Type Parameters

Chapter: Java The Complete Reference : The Java Language : Generics

A Generic Class with Two Type 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.

A Generic Class with Two Type 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, the following TwoGen class is a variation of the Gen class that has two type parameters:

 

     //A simple generic class with two type

 

     //parameters: T and V.

 

class TwoGen<T, V> { T ob1;

 

V ob2;

 

     //Pass the constructor a reference to an object of type T and an object of type V.

     TwoGen(T o1, V o2) {

 

ob1 = o1; ob2 = o2;

 

}

 

     //Show types of T and V.

 

void showTypes() { System.out.println("Type of T is " +

 

ob1.getClass().getName());

 

System.out.println("Type of V is " + ob2.getClass().getName());

 

}

 

T getob1() { return ob1;

 

}

 

V getob2() { return ob2;

 

}

 

}

 

// Demonstrate TwoGen.

class SimpGen {

public static void main(String args[]) {

 

TwoGen<Integer, String> tgObj =

 

new TwoGen<Integer, String>(88, "Generics");

 

     //Show the types.

     tgObj.showTypes();

 

     //Obtain and show values.

 

      int v = tgObj.getob1();

 

System.out.println("value: " + v);

 

String str = tgObj.getob2(); System.out.println("value: " + str);

 

}

The output from this program is shown here:

 

Type of T is java.lang.Integer value: 88

Type of V is java.lang.String  value: Generics

 

Notice how TwoGen is declared:

 

class TwoGen<T, V> {

 

It specifies two type parameters: T and V, separated by a comma. Because it has two type parameters, two type arguments must be passed to TwoGen when an object is created, as shown next:

TwoGen<Integer, String> tgObj =

 

new TwoGen<Integer, String>(88, "Generics");

 

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

 

Although the two type arguments differ in this example, it is possible for both types to be the same. For example, the following line of code is valid:

 

TwoGen<String, String> x = new TwoGen<String, String> ("A", "B");

 

In this case, both T and V would be of type String. Of course, if the type arguments were always the same, then two type parameters would be unnecessary.

 


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Language : Generics : A Generic Class with Two Type Parameters |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.