Create a generic method to match the interface and main 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 on line obj.setFilled(true);

and line obj.setFillColor(col);

. Because Shape

not Fillable

. Undefined for the Shape type.
Changing the type of an argument in a method setFilledAndAdd

to Fillable

(not Shape

) results in a compile-time error on the line add(obj, x, y);

. In this case, he needs Shape

.
All the kids Shape

I use are Fillable

. Give me a hint on how to get this method to work.
Thank.

+3


source to share


2 answers


You can use generics to say that you expect an object with two 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 fine for me.

+1


source


If you have control over the source Shape

and Fillable

, I would just rewrite so that all shapes are filled if possible. You could also use public abstract class FillableShape extends Shape implements Fillable

to keep using the type system.

Otherwise, you can use type-casting with runtime checking to make sure the form is complete:



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

      

+1


source







All Articles