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
.
我建议用这种方式构建:
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)