繁体   English   中英

实现接口的类不起作用,因为“类不是抽象的,并且不会覆盖抽象方法……”。 怎么了

[英]The class that implements the interface doesn't work because “Class is not abstract and does not override abstract method…”. What is the mistake?

Java教程中有一个“实现接口”的示例。 我已经重复了这个例子,但是没有用。 NetBeans在RectanglePlus类声明的左侧显示错误。 错误是:

rectangularplus.RectanglePlus不是抽象的,并且不会覆盖rectangleplus.Relatable中的抽象方法isLargerThan(rectangleplus.Relatable)。

我做的和教程中写的一样。 为什么显示错误? 这是我对该项目的实施。

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

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

package rectangleplus;

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

项目中的第二个文件是Main类RectanglePlus具有辅助类Point

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;
   }
}

为什么本教程示例中没有提到抽象? 教程示例是否应该没有错误地工作?

谢谢。

在接口中,您声明方法isLarger但在类中,您声明isLargerThan一个更改为另一个名称,它将很好用。

您没有在Relatable接口中正确实现isLarger()方法。 重命名isLargerThan(Relatable other)方法,使其看起来像这样:

@Override
int isLarger(Relatable other) {
}

使用@Override批注是一个好主意,它可以让您捕获问题中的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM