我刚刚开始使用 Java,并且正在通过以下网址在线查看示例: http: //docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
然后我开始实现一个接口,虽然我理解它背后的概念,但这对我来说似乎很奇怪,因为在接口声明中你只定义了它,而在实现这个接口的类中你仍然需要编写它的函数. 那么为什么要使用它呢?
我尝试了示例代码,然后更改代码以删除接口,它们的工作方式相同。所以我的问题是什么时候使用实现接口?这对我来说似乎没有必要。提前致谢!
在线示例代码:
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");
}
}
}