gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:05:55 27 4
gpt4 key购买 nike

我正在尝试创建一个以 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com