创建通用方法以适应接口和通用 parent class

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);

obj.setFilled(true); 行和第 obj.setFillColor(col); 行出现编译时错误。因为 Shape 不是 Fillable。未定义形状类型。
Fillable(不是 Shape)更改方法 setFilledAndAdd 中的参数类型会导致行 add(obj, x, y); 中出现编译时错误。在这种情况下需要 Shape
我使用的 Shape 中的所有 children 都是 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.
}

这个编译对我来说很好。