PersonQueue不是抽象的,并且不会覆盖Queue中的抽象方法addLast()

时间:2018-05-08 05:59:53

标签: java interface

我有以下界面:

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(Person person)函数替换为空public void addLast(Object o)函数时,它正在运行。

我搜索了类似的错误,但都是由声明的接口规则和实现类的不匹配引起的,但我不知道我的实现类是如何违反接口的,因为T是通用的对于类型,Person是一种类型。

2 个答案:

答案 0 :(得分:1)

声明PersonQueue以实施Queue<Person>。否则,编译器不知道泛型类型T在您的上下文中真正意味着Person。完成此更改后,所需的addLast签名将为:

public void addLast(Person o) throws IllegalStateException { ... }

(这是你已经拥有的)。

答案 1 :(得分:1)

声明Queue接口时,使用<T>这是通用对象类型参数。

因此,当您实现它时,您需要将类作为参数(即Queue<Person>)传递,如下所示:

public class PersonQueue implements Queue<Person>{
    private Person[] queue = new Person[1000];
    private int curIndex = 0;

    @Override
    public void addLast(Person person) throws IllegalStateException{
        if(queue.length > curIndex){
            queue[curIndex] = person;
            curIndex++;
        }else{
            throw new IllegalStateException("Queue is already full");
        }
    }

}