Java™ 教程(實現接口)

實現接口

要聲明實現接口的類,請在類聲明中包含implements子句,你的類能夠實現多個接口,所以implements關鍵字後面跟着由類實現的接口的逗號分隔列表,按照慣例,若是有extends子句,則implements子句緊跟其後。segmentfault

樣例接口,Relatable

考慮一個定義如何比較對象大小的接口。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);
}

若是你但願可以比較相似對象的大小,不管它們是什麼,實例化它們的類都應該實現Relatableui

若是有某種方法來比較從類中實例化的對象的相對「大小」,任何類均可以實現Relatable,對於字符串,它能夠是字符數,對於書籍,它能夠是頁數,對於學生來講,它多是重量,等等。對於平面幾何對象,面積將是一個不錯的選擇(參見後面的RectanglePlus類),而體積適用於三維幾何對象,全部這些類均可以實現isLargerThan()方法。this

若是你知道某個類實現了Relatable,那麼你就知道能夠比較從該類實例化的對象的大小。code

實現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實例上調用 getAreaother.getArea())將沒法編譯,由於編譯器不理解 other其實是 RectanglePlus的實例。

上一篇:定義接口

下一篇:將接口用做類型

相關文章
相關標籤/搜索