Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 646
zds Avatar asked Jun 06 '26 15:06

zds


1 Answers

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.

like image 62
MadConan Avatar answered Jun 08 '26 05:06

MadConan