实现接口
原文: https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
要声明实现接口的类,请在类声明中包含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
,那么您就知道可以比较从该类实例化的对象的大小。
实现可复制接口
这是创建对象部分中提供的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: The isLargerThan
method, as defined in the Relatable
interface, takes an object of type Relatable
. The line of code, shown in bold in the previous example, casts other
to a RectanglePlus
instance. Type casting tells the compiler what the object really is. Invoking getArea
directly on the other
instance (other.getArea()
) would fail to compile because the compiler does not understand that other
is actually an instance of RectanglePlus
.