要聲明實現接口的類,請在類聲明中包含implements
子句,你的類能夠實現多個接口,所以implements
關鍵字後面跟着由類實現的接口的逗號分隔列表,按照慣例,若是有extends
子句,則implements
子句緊跟其後。segmentfault
考慮一個定義如何比較對象大小的接口。less
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
。ui
若是有某種方法來比較從類中實例化的對象的相對「大小」,任何類均可以實現Relatable
,對於字符串,它能夠是字符數,對於書籍,它能夠是頁數,對於學生來講,它多是重量,等等。對於平面幾何對象,面積將是一個不錯的選擇(參見後面的RectanglePlus
類),而體積適用於三維幾何對象,全部這些類均可以實現isLargerThan()
方法。this
若是你知道某個類實現了Relatable
,那麼你就知道能夠比較從該類實例化的對象的大小。code
這是在建立對象部分中展示的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
的實例。