如何仅当方法是java中的instanceof时才使用该方法



请检查下面的代码并告诉我该怎么做我正试图将howToColor方法仅用于实现接口(Colorable)的GeometricObjects子类

    //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;

这不起作用,因为GeometricObjects没有实现Colorable有办法做这个吗

我希望我已经通过说清楚了

我是新来的:)。

使用强制转换(由于instanceof检查,已知不会抛出ClassCastException

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

最新更新