我想拥有多个类,并希望根据用户输入构造一个类。 具体来说,我正在编写文字冒险游戏,并为玩家可以使用的每种“玩家类别”提供了一个类别。我的三个班级扩展了父级“统计”班级。
这是我的代码的一部分: (我使用打印构造函数来提高书写效率)
switch (answer) {
case 1:
{
adv.print("you are a mage");
mainCharacterMage mainCharacter = new mainCharacterMage();
break;
}
case 2:
{
adv.print("you are an assasin");
mainCharacterAssasin mainCharacter = new mainCharacterAssasin();
break;
}
case 3:
{
adv.print("you are a fighter");
mainCharacterFighter mainCharacter = new mainCharacterFighter();
break;
}
default:
adv.print("error wrong answer");
break;
}
String printThis = Integer.toString(mainCharacter.getHealth());
adv.print("your health is "+printThis);
答案 0 :(得分:2)
我假定这三个子类的父类称为MainCharacter
。
首先,mainCharacter
的类型必须为MainCharacter
,除非您愿意每次使用instanceof
进行mainCharacter
检查和强制转换。您需要对mainCharacter
进行的每个操作都必须在MainCharacter
中定义,而不是在子类中定义。
第二,您需要在mainCharacter
之外声明switch
,然后在switch
中进行定义:
MainCharacter mainCharacter; // Declare it outside
switch (answer) {
case 1:
{
adv.print("you are a mage");
mainCharacter = new MainCharacterMage(); // Then define it on the inside
break;
}
case 2:
{
adv.print("you are an assasin");
mainCharacter = new MainCharacterAssasin();
break;
}
case 3:
{
adv.print("you are a fighter");
mainCharacter = new MainCharacterFighter();
break;
}
default:
adv.print("error wrong answer");
break;
}
答案 1 :(得分:1)
可能是这样的
public interface Character {
// here is all common method of your Character
}
public class CharacterFactory {
private class CharacterMage implements Character {
// here is implementation
}
private class CharacterAssasin implements Character {
// here is implementation
}
public Character createCharacter(String characterName) {
switch (characterName) {
case "Mage":
return new CharacterMage();
case "Assasin":
return new CharacterAssasin();
default:
throw new IllegalArgumentException("Incorrect character type " + characterName);
}
}
答案 2 :(得分:0)
根据类之间的区别,可以使用一个MainCharacter class
和每个类不同的工厂方法来完成。
例如,像这样设置MainCharacter类:
public class MainCharacter{
public int health;
public int damage;
// etc.
public static MainCharacter buildMage(){
health = 5;
damage = 20;
// etc.
}
public static MainCharacter buildAssassin(){
health = 10;
damage = 10;
// etc.
}
public static MainCharacter buildMage(){
health = 20;
damage = 5;
// etc.
}
}
然后按如下所示创建MainCharacter:
switch (answer) {
case 1:
{
adv.print("you are a mage");
MainCharacter main_character = MainCharacter.buildMage();
break;
}
case 2:
{
adv.print("you are an assasin");
MainCharacter main_character = MainCharacter.buildAssassin();
break;
}
case 3:
{
adv.print("you are a fighter");
MainCharacter main_character = MainCharacter.buildFighter();
break;
}
注意:这减少了您必须创建的类的数量,但是仅当类之间的差异只是不同的初始状态时才合适。如果不同的类实际上具有固有的不同方法,那么就需要继承。