Enum类中,toString中返回的name为什么是对象名字呢?

马煜
  • 9

image.png
image.png

enum Mate {
    XH,
    XQ("小强");
    private String name = "小红";
    Mate(){};
    Mate(String name){
        this.name = name;
    }
}
System.out.println(Mate.XH); //为什么返回的是XH?
System.out.println(Mate.XQ); //为什么返回的是XQ?
回复
阅读 790
3 个回答

不是很理解你要问的点。我简单说一下我的看法吧:

1.首先是toString()方法,返回的是抽象类Enum的name属性

/**
 * Returns the name of this enum constant, as contained in the
 * declaration.  This method may be overridden, though it typically
 * isn't necessary or desirable.  An enum type should override this
 * method when a more "programmer-friendly" string form exists.
 *
 * @return the name of this enum constant
 */
public String toString() {
    return name;
}

2.其次再看name属性的含义是什么,大致意思就是name属性是enum常量的名字,如Color.REDRED.
同时该字段为final字段,意思就是赋值后无法在改变其值。而赋值则在构造方法中进行的。

/**
 * The name of this enum constant, as declared in the enum declaration.
 * Most programmers should use the {@link #toString} method rather than
 * accessing this field.
 */
private final String name;

3.构造方法:可以看到构造方法是protected的,也就是我们无法通过new关键字创建Enum对象。注释里面也说了,该构造方法是编译器去处理执行的。实际执行过程就是讲枚举常量的常量名复制给了属性name。

/**
 * Sole constructor.  Programmers cannot invoke this constructor.
 * It is for use by code emitted by the compiler in response to
 * enum type declarations.
 *
 * @param name - The name of this enum constant, which is the identifier
 *               used to declare it.
 * @param ordinal - The ordinal of this enumeration constant (its position
 *         in the enum declaration, where the initial constant is assigned
 *         an ordinal of zero).
 */
protected Enum(String name, int ordinal) {
    this.name = name;
    this.ordinal = ordinal;
}

4.最后再说我们自己创建枚举类的时候,我们是可以覆盖toString()方法的,这样就可以在输出的时候返回我们想看到的信息

public enum MyEnum {

    SUCCESS(1,"success");

    int code;
    String msg;

    MyEnum(int code,String msg) {
        this.code = code;
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "MyEnum{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                '}';
    }
}

因为你无法覆盖name

宣传栏