Java:接口和返回接口的函数的实现

Java:接口和返回接口的函数的实现,java,class,interface,implementation,Java,Class,Interface,Implementation,我在实现接口时遇到了一个问题,该接口有一个函数,该函数返回一个类的值,该类本身实现一个接口。 我有一个任务,它说我需要以这种方式实现这些特定的接口。 以下是我的界面: public interface Something { int getValue(); // unique } public interface SomethingCollection { void add(Something something); Something removeMaxValue(

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

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

public interface SomethingCollection {
    void add(Something something);
    Something removeMaxValue();
}
这是实现某个接口的类:

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)”。
我不知道如何解决这个问题,也不知道我做错了什么。如何解决此问题?

您的列表未实现
void add(某物)

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


这里还有一些需要考虑的问题:您希望节点是某物还是包含某物?

您可以在集合中使用泛型,类似这样的功能应该可以:

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

class List implements SomethingCollection<Node> {
    ...
}
接口SomethingCollection
{
公共无效添加(T某物);
public T removeMaxValue();
}
类列表实现了SomethingCollection{
...
}

那我该怎么办呢?我不能把它改成什么东西,它会工作的,因为我不能创建接口的实例。我有办法处理吗?可能类似于强制转换?您可以声明方法来接受某个对象,但将其传递给某个节点的实例,因为节点是某个对象。更常见的是,正如@YuriyP所指出的,您可以使用泛型。具体类必须重写接口中的所有方法并为其提供实现
add(Node)
不会重写
add(Something)
,因为第一个参数的类型不太一般:您不能像使用
add(Something)
一样,将
Something
作为参数传递给
add(Node)