简体   繁体   English

创建适合接口和一般父类的通用方法

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

I have the following method: 我有以下方法:

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

If I add one of the lines: 如果我添加其中一行:

setFilledAndAdd(oval, color, x, y);

Compile time error apears in line obj.setFilled(true); 编译时间错误apears in line obj.setFilled(true); and line obj.setFillColor(col); 和行obj.setFillColor(col); . Because Shape is not Fillable . 因为Shape不可Fillable Undefined for the type Shape. 未定义Shape类型。
Changing argument type in method setFilledAndAdd for Fillable (not Shape ) leads to compile time error in line add(obj, x, y); 在方法变更参数类型setFilledAndAddFillable (未Shape )导致编译线时错误add(obj, x, y); . It needs Shape in this case. 在这种情况下它需要Shape
All children of Shape I use are Fillable . 我使用的Shape所有孩子都是Fillable Give me a hint, how to get this method working. 给我一个提示,如何使这个方法工作。
Thanks. 谢谢。

If you have control over the Shape and Fillable source, I would just rewrite so that all shapes are fillable, if that is possible. 如果您可以控制ShapeFillable源,我只需重写,以便所有形状都可填充,如果可能的话。 You could also have a public abstract class FillableShape extends Shape implements Fillable instead to keep using the type system. 你也可以有一个public abstract class FillableShape extends Shape implements Fillable而不是继续使用类型系统。

Otherwise you can use a type-cast, with a runtime check to make sure the shape is 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)
}

You can use generics to say that you expect an object that has both characteristics 您可以使用泛型来表示您期望具有这两个特征的对象

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.
}

This compiles just fine for me. 这对我来说很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM