Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic class with two parameters

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading