实现接口
要声明实现接口的类,请在类声明中包含implements子句,你的类可以实现多个接口,因此implements关键字后面跟着由类实现的接口的逗号分隔列表,按照惯例,如果有extends子句,则implements子句紧跟其后。
样例接口,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对象的大小。
isLargerThan方法(在Relatable接口中定义)采用Relatable类型的对象,示例中other转换为RectanglePlus实例,类型转换告诉编译器对象到底是什么,直接在other实例上调用getArea(other.getArea())将无法编译,因为编译器不理解other实际上是RectanglePlus的实例。
上一篇:定义接口
下一篇:将接口用作类型
发表回复