我有以下界面:
public interface Queue<T>{
void addLast(T o) throws IllegalStateException;
}
然后下面的类实现它:
public class PersonQueue implements Queue{
private Person[] queue = new Person[1000];
private int curIndex = 0;
public void addLast(Person person) throws IllegalStateException{
if(queue.length > curIndex){
queue[curIndex] = person;
curIndex++;
}else{
throw new IllegalStateException("Queue is already full");
}
}
}
由于某种原因,这会导致以下错误:
.\PersonQueue.java:1: error: PersonQueue is not abstract and does not
override abstract method addLast(Object) in Queue
public class PersonQueue implements Queue{
^
1 error
当用空的 public void addLast(Object o)
函数替换我的 public void addLast(Person person)
函数时,它正在工作。
我搜索了类似的错误,但都是由声明的接口(interface)规则和实现类不匹配引起的,但是我不明白我的实现类如何违反接口(interface),因为 T
是类型的泛型,Person
是一种类型。
最佳答案
声明PersonQueue
实现Queue<Person>
。否则,编译器不知道泛型类型 T
真正的意思是Person
在你的情况下。进行此更改后,所需的 addLast
签名将是:
public void addLast(Person o) throws IllegalStateException { ... }
(这是您已经拥有的)。
关于java - PersonQueue 不是抽象的,不会重写 Queue 中的抽象方法 addLast(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226825/