Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
要声明实现接口的类,请在类声明中包含 implements 子句。你的类可以实现多个接口,因此 implements 关键字后跟一个以逗号分隔的类实现的接口列表。按照规范,implements 子句跟在 extends 子句后面(如果有)。
考虑一个定义如何比较对象大小的接口。
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,那么你就知道可以比较从该类实例化的对象的大小。
这是 Creating Objects 部分中提供的 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 对象的大小。
isLargerThan 方法,如 Relatable 接口中所定义,采用 Relatable 类型的对象。代码行(在前面的示例中以粗体显示)将 other 转换为 RectanglePlus 实例。类型转换告诉编译器对象到底是什么。直接在 other 实例(other.getArea())上调用 getArea 将无法编译,因为编译器不理解 other 实际上是 RectanglePlus 的一个实例。