实现interface
要声明实现interface的类,请在类声明中包含implements
子句。您的类可以实现多个interface,因此implements
关键字后是该类实现的interface的逗号分隔列表。按照惯例,implements
子句在extends
子句之后(如果有的话)。
相关的示例interface
考虑一个定义如何比较对象大小的interface。
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
,那么您就可以比较从该类实例化的对象的大小。
实现相关interface
这是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
对象的大小。
Note:
Relatable
interface中定义的isLargerThan
方法采用Relatable
类型的对象。在上一个示例中以粗体显示的代码行将other
强制转换为RectanglePlus
实例。类型转换告诉编译器对象实际上是什么。直接在other
实例(other.getArea()
)上调用getArea
将无法编译,因为编译器无法理解other
实际上是RectanglePlus
的实例。