我有一个对象数组,其中一些使用扩展版本,其中包含基类中不可用的函数。当数组是由基类定义时,如何通过数组调用该函数?
示例
Shape[] shapes = new Shape[10];
shapes[0] = new Circle(10) //10 == radius, only exists in circle class which extends Shape
shapes[0].getRadius(); //Gives me a compilation error as getRadius() doesn't exist in the
Shape class, only in the extended Circle class. Is there a way around this?
最佳答案
Shape
类不包含方法 getRadius
,因此无需将 Shape
对象转换为 Circle
,该方法将不可见。所以你应该使用这个:
((Circle)shapes[0]).getRadius();
关于Java - 通过对象数组调用扩展类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285130/