实现接口

原文: https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html

要声明实现接口的类,请在类声明中包含implements子句。您的类可以实现多个接口,因此implements关键字后跟一个逗号分隔的类实现的接口列表。按照惯例,implements子句遵循extends子句,如果有的话。

样例接口,可重复

考虑一个定义如何比较对象大小的接口。

  1. public interface Relatable {
  2. // this (object calling isLargerThan)
  3. // and other must be instances of
  4. // the same class returns 1, 0, -1
  5. // if this is greater than,
  6. // equal to, or less than other
  7. public int isLargerThan(Relatable other);
  8. }

如果您希望能够比较类似对象的大小,无论它们是什么,实例化它们的类都应该实现Relatable

如果有某种方法来比较从类中实例化的对象的相对“大小”,任何类都可以实现Relatable。对于字符串,它可以是字符数;对于书籍,它可以是页数;对于学生来说,它可能是重量;等等。对于平面几何对象,区域将是一个不错的选择(参见后面的RectanglePlus类),而体积适用于三维几何对象。所有这些类都可以实现isLargerThan()方法。

如果您知道某个类实现了Relatable,那么您就知道可以比较从该类实例化的对象的大小。

实现可复制接口

这是创建对象部分中提供的Rectangle类,为实现Relatable而重写。

  1. public class RectanglePlus
  2. implements Relatable {
  3. public int width = 0;
  4. public int height = 0;
  5. public Point origin;
  6. // four constructors
  7. public RectanglePlus() {
  8. origin = new Point(0, 0);
  9. }
  10. public RectanglePlus(Point p) {
  11. origin = p;
  12. }
  13. public RectanglePlus(int w, int h) {
  14. origin = new Point(0, 0);
  15. width = w;
  16. height = h;
  17. }
  18. public RectanglePlus(Point p, int w, int h) {
  19. origin = p;
  20. width = w;
  21. height = h;
  22. }
  23. // a method for moving the rectangle
  24. public void move(int x, int y) {
  25. origin.x = x;
  26. origin.y = y;
  27. }
  28. // a method for computing
  29. // the area of the rectangle
  30. public int getArea() {
  31. return width * height;
  32. }
  33. // a method required to implement
  34. // the Relatable interface
  35. public int isLargerThan(Relatable other) {
  36. RectanglePlus otherRect
  37. = (RectanglePlus)other;
  38. if (this.getArea() < otherRect.getArea())
  39. return -1;
  40. else if (this.getArea() > otherRect.getArea())
  41. return 1;
  42. else
  43. return 0;
  44. }
  45. }

因为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.