我有一个对象数组,其中一些对象使用扩展版本,该扩展版本包含基类中不提供的功能。当基类定义数组时,如何通过数组调用该函数?
例子
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句