简体   繁体   中英

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); and line obj.setFillColor(col); . Because Shape is not Fillable . Undefined for the type Shape.
Changing argument type in method setFilledAndAdd for Fillable (not Shape ) leads to compile time error in line add(obj, x, y); . It needs Shape in this case.
All children of Shape I use are 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. You could also have a public abstract class FillableShape extends Shape implements Fillable instead to keep using the type system.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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