【发布时间】: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