首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现接口的类不能工作,因为"Class不是抽象的,也不覆盖抽象方法.“。这是什么错误?

实现接口的类不能工作,因为"Class不是抽象的,也不覆盖抽象方法.“。这是什么错误?
EN

Stack Overflow用户
提问于 2012-05-15 13:48:49
回答 2查看 632关注 0票数 1

Java教程中有一个“实现接口”示例。我重复了这个例子,但它不起作用。NetBeans显示了RectanglePlus类声明左边的错误。错误是:

rectangleplus.RectanglePlus不是抽象的,也不覆盖rectangleplus.Relatable中的抽象方法isLargerThan(rectangleplus.Relatable)。

我做的和在教程中写的一样。为什么它显示了错误?这是我的项目执行情况。

  1. 该项目的名称是RectanglePlus
  2. 包的名称是rectangleplus

该项目中的第一个文件是Interface Relatable

代码语言:javascript
复制
package rectangleplus;

public interface Relatable {
   int isLarger(Relatable other);   
}

项目中的第二个文件是主类RectanglePlus和助手类Point

代码语言:javascript
复制
package rectangleplus;

public class RectanglePlus implements Relatable {

    public int width = 0;
    public int height = 0;
    public Point origin;

    // four constructors
    public RectanglePlus() {
        origin = new Point(0, 0);
    }
    public RectanglePlus(Point p) {
        origin = p;
    }
    public RectanglePlus(int w, int h) {
        origin = new Point(0, 0);
        width = w;
        height = h;
    }
    public RectanglePlus(Point p, int w, int h) {
        origin = p;
        width = w;
        height = h;
    }

    // a method for moving the rectangle
    public void move(int x, int y) {
        origin.x = x;
        origin.y = y;
    }

    // a method for computing
    // the area of the rectangle
    public int getArea() {
        return width * height;
    }

    // a method required to implement
    // the Relatable interface
    public int isLargerThan(Relatable other) {
        RectanglePlus otherRect 
            = (RectanglePlus)other;
        if (this.getArea() < otherRect.getArea())
            return -1;
        else if (this.getArea() > otherRect.getArea())
            return 1;
        else
            return 0;               
    }

   public static void main(String[] args) {
      // TODO code application logic here
   }
}

class Point {
   int top;
   int left;
   int x;
   int y;

   public Point(int t, int l) {
      top = t;
      left = l;
   }
}

为什么在本教程示例中没有提到抽象?该教程示例在没有手套的情况下工作吗?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-15 13:50:47

在接口中,您声明方法isLarger,但是在声明isLargerThan的类中,将其中一个更改为另一个名称,这样就可以了。

票数 5
EN

Stack Overflow用户

发布于 2012-05-15 13:50:57

您没有在isLarger()接口中正确地实现Relatable方法。重命名isLargerThan(Relatable other)方法,如下所示:

代码语言:javascript
复制
@Override
int isLarger(Relatable other) {
}

使用@Override注释是个好主意,它允许您捕获问题中的错误。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10602160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档