2016-12-07 85 views
0

我想實例化一個對象(在「Ship」類的「EmptySea」子類中創建)到另一個「海洋」類中以用「EmptySea」對象填充數組。Java - 訪問不同類中的子類構造函數

錯誤是「EmptySea無法解析爲某種類型」。

這裏是我的海洋類代碼:

public class Ocean { 

    // Instance variables. 
    public Ship[][] ships = new Ship[10][10]; 
    public int shotsFired; 
    public int hitCount; 

    // Constructor. 
    public Ocean() { 
     shotsFired = 0; 
     hitCount = 0; 
     for (int row = 0; row < ships.length; row++) { 
      for (int column = 0; column < ships[row].length; column++) { 
       ships[row][column] = new EmptySea(); 

public abstract class Ship { 

    // Instance variables. 
    private int bowRow; 
    private int bowColumn; 
    private int length; 
    private boolean horizontal; 
    private boolean[] hit = new boolean[4]; 

    // No constructor needed for Ship class. 

    // Methods (too many to show). 

    public class EmptySea extends Ship { 

     // Constructor. 
     EmptySea() { 
      length = 1; 
     } 

     // Inherited methods to define. 
     int getLength() { 
      return length = 1; 
     } 

     String getShipType() { 
      return "Empty"; 
     } 

     @Override 
     boolean shootAt(int row, int column) { 
      return false; 
     } 

     @Override 
     boolean isSunk() { 
      return false; 
     } 

     @Override 
     public String toString() { 
      return "-"; 
     } 
    } 

的船舶陣列已經正確聲明爲海洋類的一個實例變量。基本上,它不讓我把EmptySea()對象(「Ship」類和它的「EmptySea」子類的代碼正確運行)。

在這種情況下,我需要以某種方式引用超類嗎?

如果有一個更簡單的方法來做到這一點,我不能這樣做(這種方式是在作業中指定的)。

+0

評論是不適合擴展討論;這個對話已經[轉移到聊天](http://chat.stackoverflow.com/rooms/130016/discussion-on-question-by-broncosaurus-java-accessing-a-subclass-constructor-i)。 –

回答

相關問題