gpt4 book ai didi

java - 涉及子类的多态性

转载 作者:行者123 更新时间:2023-12-01 23:46:22 24 4
gpt4 key购买 nike

我有一个任务,我应该做一个迷宫游戏。在那个游戏中我必须包含多态性。

我想在我的子类 Snake 中运行该方法,但是当我尝试从我的 Game 类访问它时它运行父类 Monsters 中的方法,而不是子类 Snake 中的方法

由于我的整个代码确实很困惑,所以我只会发布必要的代码,如果需要上下文,我可以发布更多代码。

我的父类:

package tag1;
import textio.SysTextIO;
import textio.TextIO;

public class Monsters {

TextIO io = new TextIO(new SysTextIO());

public void fight(){
io.put("You have encountered a Monster, will you fight it for a
potential reward?");
}

}

我的子类 - 这个类中的方法是我想要运行的方法

package tag1;
import java.util.ArrayList;
public class Snake extends Monsters {

public void fight(Player p, ArrayList<String>currentInventory) {


boolean condition = true;
String choice;
io.put("You have encountered a resting SNAKE, will you fight it for a
potential reward? Y/N \n");
choice = io.get();
while (condition) {
switch (choice) {
case "y":
io.put("The snake seems to realize your intentions, it looks like it is going to bite, \n"
+ " will you punch it or stomp on it? type P/S \n");
choice = io.get();
if (choice.equals("P")) {
io.put("You got too close, and the snake bit you! , and you lost 20 health!\n");
p.setHealth(p.getHealth()-20);
io.put("you Currently have " + p.getHealth());
//Alternativt kan man give personen et vigtigt ITEM senere i spillet, med et andet
//dyr fra Monster superklasssen
} else if(choice.equals("S")){
io.put("You succesfully killed the snake, with your stomp, and discover"
+ "a healthpotion underneath the snake!\n");
currentInventory.add("healtpotion");
io.put("Healthpotion added to inventory - to use healthpotion type HP");
} condition = false;
break;
case "n":
io.put("you silently move around, as the snake rests \n");
condition = false;
break;
default:
io.put("Seems like you have entered something invalid, type Y / N \n");
choice = io.get();
break;
}

}
}
}

在我的游戏类中我有这个方法

public void monsterFight(Player p, ArrayList<Room> roomList){
if (p.getCurrentRoom().equals(roomList.get(1))) {
fightMonsters(snakeObject);
}
}

-->

public void fightMonsters(Monsters variabel){
variabel.fight();
}

但是这个gos方法引用的是我的父类版本的fight()而不是子类版本?

最佳答案

仅当被重载的方法和重载的方法具有相同的签名(即相同的参数类型和相同的返回类型)时,方法重载才有效。

Snake 中的方法有两个参数,而 Monsters 中的方法根本没有参数,因此它没有重载。

当你调用Snake.fight()时,会搜索这样的方法但没有找到(没有方法被调用fight()并且接受零个参数),所以调用父方法。

奖金:
Monsters 类看起来像是所有怪物类型(例如蛇、骷髅、妖精或其他类型)的简单父类,永远不应该实例化它们。在这种情况下,最好将其设为抽象,根本不实现任何方法,这样您就不会错误地调用它的方法。

关于java - 涉及子类的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46747484/

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