私は、同等のものを格納する汎用Javaクラスを持っています:
public class MyGenericStorage<T extends Comparable<T>> {
private T value;
public MyGenericStorage(T value) {
this.value = value;
}
//... methods that use T.compareTo()
}
Person という抽象クラスもあります。
public abstract class Person implements Comparable<Person>
および 2 つの具象サブクラス、Professor と Student:
public class Professor extends Person
public class Student extends Person
このように MyGenericStorage を作成しようとすると、エラーが発生します。
//error: type argument Student is not within bounds of type-variable T
MyGenericStorage<Student> studStore = new MyGenericStorage<Student>(new Student());
//this works:
MyGenericStorage<Person> persStore = new MyGenericStorage<Person>(new Student());
これは、ジェネリックの理解に根本的な問題があるためだと思います。誰かが私にこれを説明できますか、また、それを修正する方法はありますか?
編集:
MyGenericStorage を次のように変更しました。
public class MyGenericStorage<T extends Comparable<? super T>>
そして今、それはうまくいくようです。誰かが理由を説明できますか?