簡體   English   中英

創建適合接口和一般父類的通用方法

[英]Create general method to fit interface and general parent class

我有以下方法:

private void setFilledAndAdd(Shape obj, Color col, int x, int y) {
        obj.setFilled(true);    // needs interface Fillable
        obj.setFillColor(col);
        add(obj, x, y);         // needs children of Shape (or Shape itself)
    }

如果我添加其中一行:

setFilledAndAdd(oval, color, x, y);

編譯時間錯誤apears in line obj.setFilled(true); 和行obj.setFillColor(col); 因為Shape不可Fillable 未定義Shape類型。
在方法變更參數類型setFilledAndAddFillable (未Shape )導致編譯線時錯誤add(obj, x, y); 在這種情況下它需要Shape
我使用的Shape所有孩子都是Fillable 給我一個提示,如何使這個方法工作。
謝謝。

如果您可以控制ShapeFillable源,我只需重寫,以便所有形狀都可填充,如果可能的話。 你也可以有一個public abstract class FillableShape extends Shape implements Fillable而不是繼續使用類型系統。

否則,您可以使用類型轉換,並通過運行時檢查來確保形狀是可填充的:

if(obj instanceof Fillable){
    ((Fillable) obj).setFilled(true);    
    ((Fillable) obj).setFillColor(col);
    add(obj, x, y);         
} else {
    // show an error message or something 
    // (or just draw the shape without filling it, if you want)
}

您可以使用泛型來表示您期望具有這兩個特征的對象

private  <T extends Shape & Fillable> void setFilledAndAdd(T obj, Color color, int x, int y){
    obj.setFilled(true);    // needs interface Fillable
    obj.setFillColor(color);
    add(obj, x, y);
}

private void add(Shape s, int x, int y){
    // whatever code you have goes here.
}

這對我來說很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM