Java – 通过对象数组在扩展类中调用函数
我有一个对象数组,其中一些使用扩展版本,其中包含基类中没有的函数。 当数组由基类定义时,如何通过数组调用该函数?
例
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();
如果您确定您的对象属于给定的子类,请使用强制转换:
((Circle)shapes[0]).getRadius();
试试这个
if (shapes[0] instanceof Circle) ((Circle)shapes[0]).getRadius();