以下のような方法を見たことがあります。
protected <T extends ABC> T save( T Acd, boolean en) {
これは何をするものですか?このようなメソッド宣言は、Javaでは何と呼ばれているのですか?
つまり、ABC
オブジェクトか ABC
の子クラスを送る必要があり、他のクラスは使用できません。また、Acd
変数は ABC
クラスのメソッドを使用することができますが、それは save
メソッドを含むクラスから見えるものです。
これは、 T
クラスがインターフェースを拡張している場合に便利です。例えば、オブジェクトの配列のソートを行うクラスを作成する場合、このクラスは Comparable
インターフェースを実装していなければなりません。
class Class1 implements Comparable<Class1> {
//attributes, getters and setters...
int x;
//implementing the interface...
public int compareTo(Class1 c1) {
//nice implementation of compareTo
return (this.x > c1.x)? 1 : (this.x < c1.x) ? 0 : -1;
}
}
class Class2 {
int x;
}
public class Sorter<T extends Comparable<T>> {
public static void insertionSort(T[] array) {
//good implementation of insertion sort goes here...
//just to prove that you can use the methods of the Comparable interface...
array[0].compareTo(array[1]);
}
public static void main(String[] args) {
Class1[] arrC1 = new Class1[5];
Class2[] arrC2 = new Class2[5];
//fill the arrays...
insertionSort(arrC1); //good!
insertionSort(arrC2); //compiler error!
}
}
これがジェネリックスだ型付きジェネリックス!?