Spaces:
Running
Running
interface Pair<T1, T2> { T1 getFirst(); T2 getSecond(); }
Browse files
Week 7: Enum, Generic Type, Streams, write to file, class diagram/06A. Generics in Interface Classes++
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A 'generic type' can also be defined for an 'interface class', for example:
|
| 2 |
+
|
| 3 |
+
interface Pair<T1, T2> {
|
| 4 |
+
T1 getFirst();
|
| 5 |
+
T2 getSecond();
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
Now the types can either be fixed when writing the class implementing the interface…
|
| 10 |
+
|
| 11 |
+
class StudentPair implements Pair<Student, Student> {
|
| 12 |
+
|
| 13 |
+
private Student s1;
|
| 14 |
+
private Student s2;
|
| 15 |
+
|
| 16 |
+
public StudentPair(Student s1, Student s2) {
|
| 17 |
+
this.s1 = s1;
|
| 18 |
+
this.s2 = s2;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
@Override
|
| 22 |
+
public Student getFirst() {
|
| 23 |
+
return s1;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
@Override
|
| 27 |
+
public Student getSecond() {
|
| 28 |
+
return s2;
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
...or also write the implementing class 'generically typed',
|
| 38 |
+
in which case the type is given only when an object is created from the class:
|
| 39 |
+
|
| 40 |
+
class Tuple<T1, T2> implements Pair<T1, T2> {
|
| 41 |
+
|
| 42 |
+
private T1 first;
|
| 43 |
+
private T2 second;
|
| 44 |
+
|
| 45 |
+
public Tuple(T1 first, T2 second) {
|
| 46 |
+
this.first = first;
|
| 47 |
+
this.second = second;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
@Override
|
| 51 |
+
public T1 getFirst() {
|
| 52 |
+
return first;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
@Override
|
| 56 |
+
public T2 getSecond() {
|
| 57 |
+
return second;
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
Example of using the class:
|
| 65 |
+
public static void main(String[] args) {
|
| 66 |
+
Tuple<Integer, Double> numbers = new Tuple<>(10, 0.25);
|
| 67 |
+
System.out.println(numbers.getFirst());
|
| 68 |
+
System.out.println(numbers.getSecond());
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
The program prints:
|
| 73 |
+
10
|
| 74 |
+
0.25
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|