Java - 通过对象数组调用扩展类中的函数

标签 java arrays function class extends

我有一个对象数组,其中一些使用扩展版本,其中包含基类中不可用的函数。当数组是由基类定义时,如何通过数组调用该函数?

示例

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/

相关文章:

java - 将类转换为字节数组时出错,反之亦然?

java - 通过套接字接收并打印字符串数组对象

java - Java 与 Linux 操作系统入门

java - 如何计算我的类(class)中的年份差异?

Java贪吃蛇游戏——重画特定的drawString()方法

java - 如何使用绝对路径从 Java 运行 Python 文件?

c - 将文本文件读入数组,通过函数打印

c - 如何在 C 中不使用指针的情况下通过函数传递 2D 数组

python - 在 python 中具有任意数量的参数和命名默认值

javascript - 使用 return 关键字而不是仅使用 console.log 函数并仅传递参数有什么区别?