Java教程中有一个“实现接口”示例。我重复了这个例子,但它不起作用。NetBeans显示了RectanglePlus类声明左边的错误。错误是:
rectangleplus.RectanglePlus不是抽象的,也不覆盖rectangleplus.Relatable中的抽象方法isLargerThan(rectangleplus.Relatable)。
我做的和在教程中写的一样。为什么它显示了错误?这是我的项目执行情况。
RectanglePlus。rectangleplus。该项目中的第一个文件是Interface Relatable
package rectangleplus;
public interface Relatable {
int isLarger(Relatable other);
}项目中的第二个文件是主类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;
}
}为什么在本教程示例中没有提到抽象?该教程示例在没有手套的情况下工作吗?
谢谢。
发布于 2012-05-15 13:50:47
在接口中,您声明方法isLarger,但是在声明isLargerThan的类中,将其中一个更改为另一个名称,这样就可以了。
发布于 2012-05-15 13:50:57
您没有在isLarger()接口中正确地实现Relatable方法。重命名isLargerThan(Relatable other)方法,如下所示:
@Override
int isLarger(Relatable other) {
}使用@Override注释是个好主意,它允许您捕获问题中的错误。
https://stackoverflow.com/questions/10602160
复制相似问题