java - 初始化抽象类的一般变体

标签 java inheritance abstract-class

我有两个抽象类:CharWeapon。每个都有两个衍生类别:国王巨魔,以及俱乐部

角色总是拥有武器,但未指定类型。因此,在构建 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/

相关文章:

java - 如何在android中使底部导航栏不透明?

c++ - 在模板中使用派生类并将其存储到基类的 vector 中

Javascript - 理解 Object.create 和 Object.call(this)

java - 在Java中为抽象类创建构造函数有什么用?

c# - 接口(interface)中具有不同参数的策略模式 (C#)

java - 接口(interface)如何返回其自身的严格实现

java - JTable 上的鼠标监听器触发时组件位置无效

java - JPA 1.0 Hibernate & Derby HashMap 与 Enum 键用法

java - 继承 super() 构造函数中的第一条语句

c# - C# 中是否可以使用类初始值设定项?