实现一个接口
要声明一个实现接口的类,在类声明中包含一个implements子句。你的类可以实现多个接口,所以implements关键字后面是一个由类实现的接口的逗号分隔列表。按照惯例,implements子句紧跟着extends子句,如果有的话。
一个简单的接口,Relatable
考虑使用一个接口来定义如何比较对象的大小。
public interface Relatable {
// this (object calling isLargerThan)
// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater than,
// equal to, or less than other
public int isLargerThan(Relatable other);
}
如果您想要比较类似对象的大小,无论它们是什么,实例化它们的类都应该实现Relatable。
如果有一些方法来比较从类中实例化的对象的相对“大小”,任何类都可以实现Relatable 。对于字符串,它可以是字符数 ; 对于书籍,可以是页数 ; 对于学生来说,它可能是重量 ; 等等。对于平面几何对象,面积区域是一个很好的选择(参见下面的RectanglePlus类),而体积可以用于三维几何对象。所有这些类都可以实现isLargerThan()方法。 如果你知道一个类实现了Relatable,那么你知道你可以比较从该类实例化的对象的大小。
实现接口Relatable
这是在“创建对象”部分中呈现的Rectangle类,重写为实现“Relatable”的对象。
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;
}
}
因为RectanglePlus实现了Relatable,所以可以比较两个RectanglePlus对象的大小。
注意:在“Relatable”接口中定义的isLargerThan方法采用类型为Relatable的对象。在前面的例子中用粗体显示的代码行将另外一个代码转换为一个RectanglePlus实例。类型转换告诉编译器该对象真的是什么。直接在另一个实例(other.getArea())上调用getArea将无法编译,因为编译器不了解other实际上是RectanglePlus的一个实例。