我試圖創建一個以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");
}
但代碼沒有注意到什麼類型的任何飲片的是,所以我不能正確地投他們
請問你能展示你的類定義嗎? –
我不知道instanceof關鍵字,基本上解決了我的問題,謝謝 –