枚举没有在构造函数

时间:2017-11-02 18:55:19

标签: java

我尝试使用简单的细节构建一些类似Dota2的类。我陷入了困境,我需要在Main中使用我的英雄属性,但是它的构造函数不起作用。以下是Hero类的代码:

 enum attribute {
    Strength, Intelligence, Agility
 };

public class Hero extends Unit {
private int level;
private static int str;
private static int intl;
private static int agi;
private static attribute heroAttribute;

public attribute getAttribute() {
    return heroAttribute;
}

private static int attributeDamage() {
    if (heroAttribute == attribute.Strength)
        return str;
    else if (heroAttribute == attribute.Intelligence)
        return intl;
    else
        return agi;
}

public Hero(int level, int str, int intl, int agi, attribute heroAttribute) {
    super(200 + 20 * str, attributeDamage());
    System.out.println("A hero has been spawned.");
}

}

和主要:

public class Main {
    public static void main(String[] args) {

        Hero h1= new Hero(25,400,30,30,attribute.Agility);
        System.out.println(h1.getAttribute());


    }
}

我得到的是我有null"属性"值。

2 个答案:

答案 0 :(得分:0)

尝试将此属性设置为不带静态,并启动这些属性......

private int str;
private int intl;
private int agi;
private attribute heroAttribute;

public Hero(int level, int str, int intl, int agi, attribute heroAttribute) {
   this.str = str;
   this.intl = intl;
   this.ai = agi;
   this.heroAttribute = heroAttribute;
   super(200 + 20 * str, attributeDamage());
System.out.println("A hero has been spawned.");
}

答案 1 :(得分:0)

我建议您创建包含这3个属性的新枚举类,然后实现它们。 顺便说一句,所有枚举实体应该是大写的:强度,敏捷,智能

public enum HeroAttribute {
        STRENGTH("str"),
        AGILITY("agi"),
        INTELLIGENT("intl");

        private String literal;

        HeroAttribute(String literal) {
            this.literal = literal;
        }

        public String getLiteral() {
            return literal;
        }
    }