【问题标题】:Java: Implementation of interfaces and functions that returns interfacesJava:实现接口和返回接口的函数
【发布时间】:2019-12-17 09:34:38
【问题描述】:

我在实现接口时遇到问题,该接口有一个函数,该函数返回一个实现自身接口的类的值。 我有一个任务说我需要以这种方式实现那些特定的接口。 这些是我的界面:

public interface Something {
    int getValue();  // unique
}

public interface SomethingCollection {
    void add(Something something);
    Something removeMaxValue();
}

这是实现Something接口的类:

public class Node implements Something {
    private int value;
    private Node next;

    public Node(int value) { 
        this.value = value;
        this.next = null;
    }

    public Node(int value, Node next) { 
        this.value = value;
        this.next = next;
    }

    public int getValue() {
        return this.value;
    }

    public Node getNext() {
        return this.next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

这是实现SomethingCollection的类:

public class List implements SomethingCollection {
    private Node head;
    private int maxValue;

    public List() {
        this.head = null;
    }

    public List(Node p) {
        Node n = new Node(p.getValue(), p.getNext());
        this.head = n;
        this.maxValue = this.head.getValue();
    }

    public void add(Node node) {
        if (node.getValue() > this.maxValue) {
            this.maxValue = node.getValue();
        }

        node.setNext(this.head);
        this.head = node;
    }

    public Node removeMaxValue() {
        Node current = this.head;
        Node prev = this.head;

        if (this.head == null) {
            return this.head; 
        }

        while (current != null) {
            if (current.getValue() == this.maxValue) {
                prev.getNext() = current.getNext();
                return current;
            }

            prev = current;
            current = current.getNext();
        }
    }
}

我在 List 类中有这个错误:“List 不是抽象的,并且不会覆盖 SomethingCollection 中的抽象方法 add(Something)”。 我不知道如何解决这个问题以及我做错了什么。我该如何解决这个问题?

【问题讨论】:

  • 具体类必须重写并提供接口中所有方法的实现。 add(Node) 不会覆盖 add(Something),因为第一个参数的类型不太通用:你不能像 add(Something) 那样将 Something 作为参数传递给 add(Node)

标签: java class interface implementation


【解决方案1】:

您的列表没有实现void add(Something something)

当然,它确实实现了public void add(Node node),并且一个节点就是一个东西。但是你的类实现了一个接口。它必须满足该接口。并且该接口包括一个接受任何类型的东西的方法,而不仅仅是节点。

还有其他需要考虑的问题:您希望节点成为某物,还是包含某物?

【讨论】:

  • 那我该怎么办呢?我不能只是将其更改为 Something 并且它会起作用,因为我无法创建接口的实例。有什么办法可以处理吗?也许像铸造之类的?
  • 你可以声明方法接受一个Something,但是传递一个Node的实例,因为Node ISA Something。正如@YuriyP 所说,更常见的是,您可以使用泛型。
【解决方案2】:

你可以在你的集合中使用泛型,这样的东西应该可以工作:

interface SomethingCollection <T>
{
   public void add(T something);
   public T removeMaxValue();
}

class List implements SomethingCollection<Node> {
    ...
}

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 2019-02-10
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    相关资源
    最近更新 更多