在构造函数中自行分配对象的子对象

Self assign object its child object in constructor

假设我们有:

Class 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);
        }
    }

}

和ClassWeapon继承自Item

public class Weapon extends Item {

    Bullet.Type bulletType;
    int fireRate;

    public Weapon(Type type) {
        this.type = type;
    }
}

它是从这样的地方调用的:

Item item = new Item(Item.Type.PISTOL);

我其实知道 this 在 Java 中是不可分配的,但我想知道如何解决这种情况。

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

我建议这样构造:

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);
    }
}