自我在构造函数中为对象分配对象

iva*_*kov 0 java inheritance constructor variable-assignment

假设我们有:

课程Item:

public class Item {
    private Type type;

    Item(Type type) {
        this.type = type;

        if (type == Type.PISTOL || type == Type.AR || type == Type.SNIPER_RIFLE) {
            this = new Weapon(type);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

和类Weapon继承自Item:

public class Weapon extends Item {

    Bullet.Type bulletType;
    int fireRate;

    public Weapon(Type type) {
        this.type = type;
    }
}
Run Code Online (Sandbox Code Playgroud)

它从某个地方调用,如:

Item item = new Item(Item.Type.PISTOL);
Run Code Online (Sandbox Code Playgroud)

我实际上知道this在Java中不可分配,但我想知道如何解决这种情况.

如果它的类型合适,我想分配item新的Weapon.

孙兴斌*_*孙兴斌 5

我建议用这种方式构建:

public static Item create(Type type) {
    if (type == Type.PISTOL || type == Type.AR || type == Type.SNIPER_RIFLE) {
        return new Weapon(type);
    } else {
        return new Item(type);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为你有一个错字.`this = new Weapon`应该是'返回新武器',不应该吗? (2认同)