I have a generic java class that stores comparables:
public class MyGenericStorage<T extends Comparable<T>> {
private T value;
public MyGenericStorage(T value) {
this.value = value;
}
//... methods that use T.compareTo()
}
I also have an abstract class called Person:
public abstract class Person implements Comparable<Person>
and two concrete subclasses, Professor and Student:
public class Professor extends Person
public class Student extends Person
now when I want to create a MyGenericStorage like so, I get an error:
//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());
I think this is because I have a fundamental problem with understanding generics. Can someone explain this to me, and also, how to fix it?
EDIT:
I have changed MyGenericStorage to the following:
public class MyGenericStorage<T extends Comparable<? super T>>
and now it seems to work. Can someone explain why?
public class Student extends Person implements Comparable<Student>
? – Returnee