Below is the Java program which will create an enum class together with each constant and then assigns each constant entity with a strength value which will get retrieved later.
public enum Entity {
Enemy1("Enemy1") {
@Override
void setStrength(int strength) {
this.strength = strength;
}
@Override
int getStrength() {
return this.strength;
}
},
Enemy2("Enemy2") {
@Override
void setStrength(int strength) {
this.strength = strength;
}
@Override
int getStrength() {
return this.strength;
}
},
Enemy3("Enemy3") {
@Override
void setStrength(int strength) {
this.strength = strength;
}
@Override
int getStrength() {
return this.strength;
}
};
private final String name;
public int strength;
Entity(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
abstract void setStrength(int strength);
abstract int getStrength();
public static void main(String[] args) {
System.out.println("Set enemy strength: ");
for (int i = 0; i < Entity.values().length; i++) {
Entity.values()[i].setStrength(100);
}
for (int i = 0; i < Entity.values().length; i++) {
System.out.println(Entity.values()[i].name() + " : " + Entity.values()[i].getStrength());
}
}
}
After the assignment of the strength to each constant entity, the program prints those constant names together with their relative strength! Actually, you can set and get the strength of each entity outside of the constant with only a single method but I purposely created separate methods within each constant only to demonstrate to you the usage of the abstract methods.