【问题标题】:How can I access non-static methods for instances of objects stored inside of an array?如何访问存储在数组中的对象实例的非静态方法?
【发布时间】:2017-05-03 20:00:49
【问题描述】:

我正在为我的一门课程创建模拟,但遇到了一些麻烦。在这里寻找一些方向+任何提示。

到目前为止,我有两个课程,我正在寻求实现一些其他的东西。目前,我希望能够访问存储在其他类中的数组中的对象的点(x 和 y 坐标)。

【问题讨论】:

  • 你的意思是ecosystem[i][j].method();
  • 有点!我想在生态系统的 initialize() 中创建的 Carnivores 实例上调用 getCarnivoreColumn()。
  • 我已经告诉过你如何...
  • 没有。转换返回值。您必须投射对象。 ((Carnivore) ecosystem[i][j]).getCarnivoreColumn();
  • instanceof 和向下转换是代码气味。为什么没有方法getColumn,在超接口中声明并在子类中实现? Java 是一种面向对象的语言;你不妨试试面向对象编程吧?

标签: java arrays static-methods instanceof instances


【解决方案1】:
  1. 您不能在生态系统数组中存储每种动物类型的新实例,因为这些动物类型不是生态系统。为此,您需要让这些其他类扩展 Ecosystem。
  2. 我建议您将 Ecosystem 设为接口并从其他类中实现它。在接口中定义getRow()getColumn() 并在子类中覆盖它,这样每个数组元素都可以访问它并返回它们的具体实现。
  3. public static void printCarnivore() 是错误的。内部类中不能有这样的静态方法。

【讨论】:

    【解决方案2】:

    这应该可行。

    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 + ")" )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 2023-03-08
      相关资源
      最近更新 更多