java - PersonQueue 不是抽象的,不会重写 Queue 中的抽象方法 addLast()

标签 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(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/

相关文章:

javascript - 在 ES6 之前的 Typescript 中实现 Iterator<T> 的推荐方法

Java 性能测试

java - 尝试为 DynamoDB 初始化客户端时 Amazon Lambda 超时

go - 在 Go 中显式选择接口(interface)的实现方法

java - 枚举<?扩展界面>

c# - 将类方法名称作为 lambda 表达式传递

java - 使用 Spring Data Rest 和 MongoDB 更新特定字段

java - STL 库与 JCF 框架

java - "Find substring in char[]"得到意想不到的结果

java - 传递整个对象与传递原始值 -