【问题标题】:Non abstract class cannot override abstract method compareTo in Comparable?非抽象类不能覆盖Comparable中的抽象方法compareTo?
【发布时间】:2017-02-27 20:08:06
【问题描述】:

我有一个类Vertex<T>,它实现了IVertex<T>,它实现了Comparable。每当我编译我的代码时,我都会收到错误:

顶点不是抽象的,不会覆盖抽象方法 可比较中的 compareTo(IVertex)

问题在于,我无法更改界面IVertex 中的任何代码,因为这是我老师的指示。我该如何解决这个问题?我在下面包含了我的代码:

顶点:

 package student_solution;


import graph_entities.*;

import java.util.*;

public class Vertex<T> implements IVertex<T>{

  // Add an edge to this vertex.

  public void addEdge(IEdge<T> edge){

  } 

  // We get all the edges emanating from this vertex:  

    public Collection< IEdge<T> > getSuccessors(){

    }

    // See class Label for an an explanation:

    public Label<T> getLabel(){

    }

    public void setLabel(Label<T> label){

    }

  }

IVertex:

package graph_entities;

import java.util.Collection;

public interface IVertex<T> extends Comparable<IVertex<T>>
{

  // Add an edge to this vertex.

  public void addEdge(IEdge<T> edge);

  // We get all the edges emanating from this vertex:  

public Collection< IEdge<T> > getSuccessors();

  // See class Label for an an explanation:

public Label<T> getLabel();

public void setLabel(Label<T> label);

}

提前谢谢你!

【问题讨论】:

  • 好吧,实现你忘记实现的方法(即public int compareTo(IVertex&lt;T&gt; v).
  • 编译器告诉你你的类必须实现 compareTo 方法——仅此而已。
  • 仔细阅读错误信息。它说Vertex,而不是IVertex

标签: java interface abstract comparable


【解决方案1】:

正如错误提示的那样,您的类实现了一个扩展Comparableinterface。现在,为了使你的类具体化,你必须override 你的类正在实现的interfaces 的所有方法。

因此,在您的情况下,您需要做的就是覆盖 Vertex class 中的 compareTo 方法,例如:

@Override
public int compareTo(IVertex<T> o) {
    // implementation
    return 0;
}

Here 的 Oracle 关于接口和继承的文档。

【讨论】:

  • 是的,主要是,但他需要实现的方法不是compareTo(T),而是compareTo(IVertex&lt;T&gt;)。这可能是一个设计问题,具体取决于应该如何实现比较。
  • @JohnBollinger 感谢您指出这一点。我错过了 :( 是的,这很可能是一个设计问题,但由于 OP 被指示不要更改 interface,我们无能为力。
  • 谢谢!当我看到命令行错误时,我想我惊慌失措。初学者的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多