原文出自 http://www.cnblogs.com/ggjucheng/archive/2012/12/04/2802265.html
英文出自 http://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
声明一个类实现接口,要在类声明中包含一个implements语句。类可以实现多个接口,所以implements关键字尾随一个逗号隔开的由该类实现的接口。按照惯例,如果有父类继承,implements语句尾随extend语句。
一个简单的接口,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。对于strings,它可以比较字符的个数,对于书,可以比较页数,对于学生,可以比较体重等等。对于平面的几何对象,面积将是一个不错的选择(见下面的RectanglePlus类的),对于三维几何对象可以使用体积对比。所有这些类可以实现isLargerThan()方法。
实现Relatable 接口
这里是一个Rectangle接口的实现:
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类型的对象。转换other为RectanglePlus实例的那行代码。类型转换告诉编译器,对象实际是什么类型。直接调用other实例的other.getArea()方法将会失败,因为编译器不知道other真正是RectanglePlus实例。

浙公网安备 33010602011771号