爪哇 - 通过一个对象数组中调用扩展类的函数 [英] Java - Calling functions in extended classes through an object array
本文介绍了爪哇 - 通过一个对象数组中调用扩展类的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有对象,其中的一些使用含有在基类不可用的功能的扩展版本的阵列。我怎么能叫通过数组功能,当阵列是由基类中定义?
示例
图形[] =形状新的Shape [10];形状[0] =新圆(10)// 10 ==半径,只存在于它扩展型圈类形状[0] .getRadius(); //给我一个编译错误作为getRadius()中不存在
Shape类,只有在扩展Circle类。有没有解决的办法?
解决方案
图形
类不包含方法 getRadius
因此无需进行转换图形
的对象圆形
,该方法将不可见。所以,你应该用这样的:
((圆)形状[0])getRadius()。
I've got an array of objects, some of which use an extended version which contains a function not available in the base class. How can I call that function through the array when the array is defined by the base class?
Example
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
class does not contain the method getRadius
and hence without casting the object of Shape
to Circle
, the method will not be visible. So you should use this:
((Circle)shapes[0]).getRadius();
这篇关于爪哇 - 通过一个对象数组中调用扩展类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文