简体   繁体   中英

how to use a method only if its an instanceof in java

Please check the code bellow and tell me what to do I am trying to use the method howToColor only for GeometricObjects subclasses that implement the interface (Colorable)

    //GeometricObjects is an abstract class
    GeometricObjects[] array = new GeometricObjects[5];
    array[0]= new Triangle(4.0, 3.0, 5.0);
    array[1]= new Square(6.3);
    //continue for all elements...


    for (int i = 0; i < array.length; i++) {
        if(array[i] instanceof Colorable)
            array[i].howToColor;

this doesn't work because GeometricObjects doesn't implement Colorable is there a way i can do this

I hope I made it clear enogh

ps:I'm new here :).

Use a cast (which is known to not throw ClassCastException because of the instanceof check)

if(array[i] instanceof Colorable)
        ((Colorable) array[i]).howToColor;

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