Home > Blockchain >  Generic class with two parameters
Generic class with two parameters

Time:03-23

This is the question:

Create a generic class named Duo that has two parameters, A and B. Declare a variable named first of type A, and the second variable named second of type B. Create a constructor that accepts these two parameters. In the constructor, assign these parameters respectively to the declared variables.

This is the solution that I could think of:

public class Duo<T> {

    T first;
    T second;

    public Duo(T one , T two) {
        this.first = one;
        this.second = two;
    }

}

Then, when I proceed to the next question, I am stucked. This is the question:

  1. Use the Duo class in Question 4 to declare and create two objects as follows :

    a) First object called sideShape consist of respectively String type and Integer type.

    b) Second object called points consists of two Double types.

I am confused. How to call the generic class with two parameters?

This is my approach:

Duo <Object> sideShape = new Duo();  

Am I correct?

If not can you please point out my mistakes. I am really lost.

CodePudding user response:

You need two types of Geneerics:

public class Duo<P,Q> {

P first;
Q second;

public Duo(P one , Q two) {
    this.first = one;
    this.second = two;
}
}

Later you can use as follows:

Duo<String, Integer> duo = new Duo("Hello", 5);
  • Related