我有两个抽象类:Char 和Weapon。每个都有两个衍生类别:国王和巨魔,以及俱乐部和剑。
角色总是拥有武器,但未指定类型。因此,在构建 Char 类时,我无法初始化正确的类型。另外,在选择角色时,我同样无法初始化正确的类型。
Is it wrong to initialise an abstract class? How can one initialise a class of one sort and then change the variable class? Provided the new type is a trivially different inheritation of the same parent class? Or should one go about it completely differently?
很可能我什至都没有理解抽象类的概念。我是 Java 和纯 OOP 新手。
public class Player{
private Char c; // Wrong?
public void changeChar(int charID, int wepID){
switch(charID){
case 1: c = new King(wepID); break;
case 2: c = new Troll(wepID); break;
}
}
public void fight(){
c.fight();
}
}
abstract class Char{
protected String name;
public Weapon weapon; // Wrong?
Char(int wepID){
switch(wepID){
case 1: weapon = new Sword(); break;
case 2: weapon = new Club(); break;
}
}
public void fight(){
weapon.useWeapon(name);
}
}
abstract class Weapon{
protected String wepName;
public void useWeapon(String user){
System.out.println(user + " fights with " + wepName);
}
}
class Club extends Weapon{
Club(){
wepName = "Club";
}
}
class Sword extends Weapon{
Sword(){
wepName = "Sword";
}
}
class Troll extends Char{
Troll(int wepID){
super(wepID);
name = "Troll";
}
}
class King extends Char{
King(int wepID){
super(wepID);
name = "King";
}
}
最佳答案
您无法实例化抽象类。更明智的方法是为 Char
的构造函数提供一个 Weapon
实例作为参数 - 您可以简单地在 Char
中使用它。
abstract class Char{
protected String name;
public Weapon weapon;
Char(Weapon weapon){
this.weapon = weapon;
}
public void fight(){
weapon.useWeapon(name);
}
}
class Troll extends Char{
Troll(Weapon weapon){
super(weapon);
name = "Troll";
}
}
以及稍后在您的代码中:
Char troll = new Troll (new Club());
关于java - 初始化抽象类的一般变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630062/