Java™ 教程(实现接口)

7次阅读

共计 1644 个字符,预计需要花费 5 分钟才能阅读完成。

实现接口
要声明实现接口的类,请在类声明中包含 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 的实例。

上一篇:定义接口
下一篇:将接口用作类型

正文完
 0