2015-10-05 112 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();