Java is not allowing me to add a subclass of the Type declaration in this class
public class Exam<T> {
public void set(Holder<? super T> hold){
}
public T get(Holder<? extends T> holder){ return holder.get();}
public static void main (String[] args){
Exam<Question> eq = new Exam<Question>();
eq.set(new Holder<Identification>());
}
}
Where Identification is a subclass of Question.
and this how my holder class looks like
public class Holder<T> {
T item;
public void set(T item){ this.item = item; }
public T get(){return item;}
}
ERROR
The method set(Holder<? super Question>) in the type Exam<Question> is not applicable for the arguments (Holder<Identification>)
The error looks pretty self-explanatory to me – the
setmethod expects aHolder<? super Question>and you’re trying to give it a Holder of something that is a subclass ofQuestion. As written,Exam.setcould take aHolder<Object>, for example, but not aHolder<Identification>.A good way to think about
extendsandsuperin generics is in terms of assignment:T extends Foowill accept any typeTthat you could use on the right hand side of an assignment toFoowithout casting, i.e.(treat this as pseudocode – I know you’re not really allowed to
newa type varaible). Conversely,T super Fooaccepts any T you could use on the left hand side of an assignment without casting:In your specific example,
Identification i = new Question()isn’t legal without a cast, so aHolder<? super Question>parameter can’t accept aHolder<Identification>value.