我试图创建一个以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关键字,基本上解决了我的问题,谢谢 –