我刚开始的Java,并通过在线的例子会在: http://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.htmlJava为什么需要实现一个接口?
然后我得到了实现一个接口,而据我了解它背后的概念,但它似乎怪我,因为在界面声明你只定义它,并且在实现这个接口的类中,你仍然需要编写它的函数。那为什么要用它呢?
我试过了示例代码,然后更改代码以删除接口,并且它们都工作相同。所以我的问题是什么时候将使用实现接口?对我来说看起来没有必要。提前致谢!
示例代码在线:那我改成
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 class RectanglePlus {
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(RectanglePlus otherRect) {
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
public static void main(String[] args)
{
RectanglePlus newRect = new RectanglePlus(20, 30);
RectanglePlus somerect = new RectanglePlus(50, 100);
System.out.println("Area of newRect is " + newRect.getArea());
System.out.println("Area of somerect is " + somerect.getArea());
if((newRect.isLargerThan(somerect))==1)
{
System.out.println("newRect is bigger");
}
else
{
System.out.println("somerect is bigger");
}
}
}
但修改后的''那里是Relatable'预计RectanglePlus'将无法使用...... – MadProgrammer
我觉得本教程不是很清楚因为isLargerThan只能在同一类比较对象。我做了另一个名为SquarePlus的类,然后尝试使用if(newRect.isLargerThan(somesquare)== 1)比较两者。它不会工作 –