请检查下面的代码并告诉我该怎么做 我尝试仅对实现接口(interface) (Colorable) 的 GeometricObjects 子类使用 howToColor 方法
//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;
关于java - 如何仅在java中的instanceof时使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218553/