Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Subject: Java Problem 1: Generic Class 1. Create a generic class “GenericClass”

ID: 3888400 • Letter: S

Question

Subject: Java

Problem 1: Generic Class

1.

Create a generic class “GenericClass” with 3 formal type parameters.

2.

Declare 3 instance variables one of each formal type

3.

Define get and set methods for each instance variable

4.

Define toString method that displays the values of the three instance variables

5.

Declare a driver class that tests the functionality of the Generic Class

Example:

public class

Pair

<A, B>

{

A

first;

B second;

public

Pair (

A

a, B b){

first = a;

second = b;

}

public

A

getFirst(){

return

first;

}

public

B getSecond(){

return

second;

}

}

Explanation / Answer

Hi,

Please find below the code with its output. Let me know if you have any doubts in it.

GenericClass.java:

//GenericClass with 3 type parameters
public class GenericClass <A, B, C>{

//Declaring instance variables.
A first;
B second;
C third;

//Setters and getters for all instance variables
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
public C getThird() {
return third;
}
public void setThird(C third) {
this.third = third;
}

//toString method that displays values of all 3 instance variables
public String toString() {
return "first=" + first + ", second=" + second
+ ", third=" + third;
}


}


GenericClassDriver.java:

public class GenericClassDriver {

public static void main(String[] args) {
//Creating an object of our GenericClass
GenericClass<Integer, Integer, String> genericClassObject=new GenericClass<Integer, Integer, String>();;

genericClassObject.setFirst(new Integer(5));
genericClassObject.setSecond(new Integer(10));
genericClassObject.setThird(new String("Hello"));

System.out.println(genericClassObject.toString());
}

}

Output on console:

first=5, second=10, third=Hello