2017-05-03 26 views
-1

我正在爲我的一個類創建一個模擬,並且遇到了一些麻煩。在這裏尋找一些方向+任何提示。如何訪問存儲在數組內部的對象實例的非靜態方法?

到目前爲止我有兩個類,我正在尋找其他一些東西。目前,我希望能夠訪問存儲在其他類中的數組中的對象的點(x和y座標)。

+1

你的意思是'生態系統[i] [j] .method();'? – Li357

+0

那種!我想調用getCarnivoreColumn()在Ecosystem的initialize()中創建的食肉動物實例上。 – mmuso

+0

我已經告訴過你如何... – Li357

回答

-1

這應該工作。

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 + ")") 
} 
0
  1. 你不能每個那些動物類型的新實例存儲在一個生態系統的陣列,因爲這些動物類型不是生態系統。要做到這一點,你需要讓這些其他類擴展生態系統。
  2. 我建議你讓Ecosystem成爲一個接口並從其他類實現它。在接口中定義getRow()getColumn(),並在子類中覆蓋它,這樣每個數組元素都可以訪問它並返回它們的具體實現。
  3. public static void printCarnivore()是錯誤的。在內部類中不能有這樣的靜態方法。
相關問題