2015-10-05 74 views
0

我試圖創建一個以Piece類開始的程序。爲了練習的目的,每個其他課程延伸Piece。其他類包含移動塊的方法,無論是一個空格還是n個空格。Java:從父對象數組訪問子類方法

所有的作品都存儲在二維數組中,用於移動。

我的問題是,如果我製作一個Pieces數組,我不能訪問移動方法,因爲它們存儲在子類中。我也不能僅僅投射物體,因爲我有4種不同的類型,用戶可以要求移動。

這是增加了一塊板子

//adds a piece based on given type, but only if the space is clear (null) 
public void addpiece(String type, String n, String c, int x, int y){ 
    if(board[x][y] == null){ 
     if(type == "FastFlexible"){ 
      board[x][y] = new FastFlexiblePiece(n,c,x,y); 
     } 
     else if(type == "FastPiece"){ 
      board[x][y] = new FastPiece(n,c,x,y); 
     } 
     else if(type == "SlowFlexible"){ 
      board[x][y] = new SlowFlexiblePiece(n,c,x,y); 
     } 
     else if(type == "SlowPiece"){ 
      board[x][y] = new SlowPiece(n,c,x,y); 
     } 
     else{ 
      System.out.println("Invaild type"); 
     } 
    } 
} 

的代碼,這是試圖移動這塊代碼,我得到的錯誤是因爲父Piece沒有一招方法,但我想不出一種方法來獲得片段正確投射

//Move a piece, two method one for fast and one for slow 
public void movePiece(int x, int y, String direction){ 
    if(board[x][y] != null){ 
     if(board[x][y].getType().equals("SlowPiece")){ 
      board[x][y] = board[x][y].move(direction); 
     } 
     else if(board[x][y].getType().equals("SlowFlexible")){ 
      board[x][y] = board[x][y].move(direction); 
     } 
    } 
} 

還有另一種類似的方法快速件。

的構造函數slowPiece:

//Constructor 
public SlowPiece(String n, String c, int x, int y){ 
    super(n,c,x,y); 
    this.setType("SlowPiece"); 
} 

但代碼沒有注意到什麼類型的任何飲片的是,所以我不能正確地投他們

+0

請問你能展示你的類定義嗎? –

+1

我不知道instanceof關鍵字,基本上解決了我的問題,謝謝 –

回答

1

Polymorphism非常目的是爲了避免像public void movePiece(int x, int y, String direction){規定的實施編寫代碼。

board [x] [y]可以指SuperType Piece及其任何子類型,如SlowPiece,SlowFlexible,FastPiece,FastFlexible。件可以具有在類的定義中指定的抽象move行爲,而不必提供實現。 Piece類的所有子類型都爲move方法提供了自己的實現。

的方法public void movePiece(int x, int y, String direction)將簡單歸結爲這樣:

public void movePiece(int x, int y, String direction){ 
     board[x][y].move(direction); 
    } 

在運行時,move方法取決於片類的子類型動態調度。

0

我的建議是增加一個abstract method給父母Piece班。

public class Piece{ 
    public abstract void move(); 
} 

注:現在你不能直接實例化一個Piece。此代碼是非法的:

Piece p = new Piece();