Java 如何访问存储在数组中的对象实例的非静态方法?
我正在为我的一个类创建一个模拟,我遇到了一些麻烦。在这里寻找一些方向+任何提示 到目前为止,我有两个类,我希望实现其他一些东西。目前,我希望能够访问存储在另一个类中的数组中的对象的点(x和y坐标)。这应该可以Java 如何访问存储在数组中的对象实例的非静态方法?,java,arrays,static-methods,instanceof,instances,Java,Arrays,Static Methods,Instanceof,Instances,我正在为我的一个类创建一个模拟,我遇到了一些麻烦。在这里寻找一些方向+任何提示 到目前为止,我有两个类,我希望实现其他一些东西。目前,我希望能够访问存储在另一个类中的数组中的对象的点(x和y坐标)。这应该可以 if (ecosystem[i][j] instanceof Carnivore) { Carnivore.printCarnivore(); System.out.print(" | "); int x = (Carnivore) ecosystem[i][j].
if (ecosystem[i][j] instanceof Carnivore) {
Carnivore.printCarnivore();
System.out.print(" | ");
int x = (Carnivore) ecosystem[i][j].getCarnivoreRow();
int y = (Carnivore) ecosystem[i][j].getCarnivoreColumn();
System.out.println("Coordinates: (" + x + ", " + y + ")" )
}
getRow()
和getColumn()
并在子类中重写它,这样每个数组元素都可以访问它并返回它们的具体实现公共静态void printcanivore()
是错误的。在内部类中不能有这样的静态方法你的意思是
生态系统[i][j].method()代码>?有点!我想对生态系统中在initialize()中创建的食肉动物实例调用getCarnivoreColumn()。我已经告诉过你如何…不。这将强制转换返回值。你必须投射这个物体<代码>((食肉动物)生态系统[i][j])。getCarnivoreColumn()代码>instanceof
和Downcast都是代码气味。为什么不在超级接口中声明并在子类中实现方法getColumn
?Java是一种面向对象的语言;你不妨试试面向对象编程,嗯?