This question already has answers here:
Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
(17个答案)
2年前关闭。
我在这里使用接口时遇到问题。当我尝试将列表“答案”设置为ArrayList时,出现错误:
类型QuestionImpl的setAnswers(List)方法不适用于参数(ArrayList)
在我看来,我想在这种情况下使用接口,以便稍后指定实现。
回答界面:
(17个答案)
2年前关闭。
我在这里使用接口时遇到问题。当我尝试将列表“答案”设置为ArrayList时,出现错误:
类型QuestionImpl的setAnswers(List)方法不适用于参数(ArrayList)
在我看来,我想在这种情况下使用接口,以便稍后指定实现。
public class QuestionImpl extends QuestionAnswerImpl implements Comparable<Object>, Question {
private List<Answer> answers;
public QuestionImpl(){
setAnswers(new ArrayList<AnswerImpl>());
}
@Override
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
@Override
public List<Answer> getAnswers() {
// TODO Auto-generated method stub
return answers;
}
回答界面:
public interface Answer {
int i=0;
public int compareTo(Object object1);
public String getListValu(int question);
public void setNum(int i);
}
Answer class info (most of the code is irrelevant here)
public class AnswerImpl extends QuestionAnswerImpl implements
Comparable<Object>, Answer {...}
最佳答案
您的类型参数错误。您的方法需要一个Answer
类型的列表,但是您传递的AnswerImpl
列表是不同的。这是两种不同的类型。您可以通过使用通用类型参数来解决此问题,例如
@Override
public void setAnswers(List<? extends Answer> answers) {
this.answers = answers;
}
关于java - 使用List接口(interface),其中给定的类型是将通过setter方法实现的接口(interface)。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45883331/