Java:从父对象数组访问子类方法

标签 java arrays oop polymorphism

我正在尝试创建一个以 Piece 类开头的程序。为了练习的目的,所有其他类都扩展了 Piece。其他类包含移动棋子的方法,可以是一个空格,也可以是 n 个空格。

所有的棋子都存储在一个二维数组中,可以用来移动。

我的问题是,如果我制作一个 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");
}

但是代码没有注意到任何 Pieces 的类型,因此我无法正确地转换它们

最佳答案

Polymorphism的目标是为了避免编写类似为 public void movePiece(int x, int y, String Direction){.

指定的实现的代码。

board[x][y] 可以引用 SuperType Piece 及其任何子类型,如 SlowPiece、SlowFlexible、FastPiece、FastFlexible。 Piece 可以具有类定义中指定的抽象 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 方法根据 Piece 类的 SubType 动态调度。

关于Java:从父对象数组访问子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32953980/

相关文章:

oop - 去 "polymorphism"

java - 将结果集中的行插入到不同的数据库-Jdbc

java - 以相同的概率选择三个数字之一?

java - 判断父进程是否为终端

C++ 数组大小初始化

javascript - 按日期顺序对nodejs中的数组进行排序(从最近到最旧)

MATLAB - 创建对变量的引用(句柄?)

java - 如何通过maven导入多个Spring应用程序,其中每个依赖项位于自己的类路径上(以避免依赖项冲突)?

JavaScript 不重置循环中的变量

javascript - JS全局变量类型的区别