"延伸"枚举 [英] "extending" enum
问题描述
枚举枚举Enum1 {
A(1,2),
B(3,4);
public int a,b;
private Enum1(int a,int b){
this.a = a;
this.b = b;
}
}
枚举Enum2 {
C(6,7),
D(8,9);
public int a,b;
private Enum1(int a,int b){
this.a = a;
this.b = b;
}
}
等等...
不幸的是Enum1和Enum2已经扩展了Enum,所以不可能写出一个可以扩展的超类。
有另外一种方法来存档吗?
更新:这里是一个真实世界的例子。想想一个经典的RPG,你有物品,盔甲,武器等,给你一个奖金。
枚举武器{
SWORD(3,0,2),
AXE_OF_HEALTH(3,4,1);
//这些武器的奖金
public int力量,健康,防守;
私人武器(int strength,int health,int defense){
this.strength = strength;
this.health = health;
this.defense = defense;
}
}
枚数装甲{
SHIELD(3,1,6),
BOOTS(0,4,1);
//奖金
public int力量,健康,防守;
私人武器(int strength,int health,int defense){
this.strength = strength;
this.health = health;
this.defense = defense;
}
}
枚举扩展枚举。他们也不能扩展别的东西。但是,他们可以实现接口。
你可以使它们都实现一个通用的接口,并在接口上放置你的getA(),getB()方法。 >
I have multiple enum's that all have the same constructor and attributes, like this:
enum Enum1 {
A(1,2),
B(3,4);
public int a, b;
private Enum1(int a, int b) {
this.a = a;
this.b = b;
}
}
enum Enum2 {
C(6,7),
D(8,9);
public int a, b;
private Enum1(int a, int b) {
this.a = a;
this.b = b;
}
}
and so on... Unfortunately Enum1 and Enum2 already extend Enum, so it isn't possible to write a superclass they could extend. Is there another way to archive this?
Update: here comes a "real-world" example. Think of a classic rpg, where you have items, armour, weapons etc. which give you a bonus.
enum Weapon {
SWORD(3,0,2),
AXE_OF_HEALTH(3,4,1);
// bonus for those weapons
public int strength, health, defense;
private Weapon(int strength, int health, int defense) {
this.strength = strength;
this.health = health;
this.defense = defense;
}
}
enum Armour {
SHIELD(3,1,6),
BOOTS(0,4,1);
// bonus
public int strength, health, defense;
private Weapon(int strength, int health, int defense) {
this.strength = strength;
this.health = health;
this.defense = defense;
}
}
Enums extend Enum. They cannot also extend something else. However, they can implement interfaces.
You can make them both implement a common interface, and put your getA(), getB() methods on the interface.
这篇关于"延伸"枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!