Java枚举类

在JAVA基础的学习中学到的枚举类一般是这样的:

enum Weekday {
    SUN, MON, TUE, WED, THU, FRI, SAT;
}

而我在实际中碰到的枚举类是这样的:

import lombok.AllArgsConstructor;

@AllArgsConstructor
public enum Test {

    SAT("sat"),
    SUB("sub");
    
    private String test;
}


public class Test2 {
    public static void main(String[] args) {
        // 调用
        System.out.print(Test.SUB.name());
    }
}

一个疑问是在类中声明时的方式:SAT("sat"),不是传统的public String xxx=xxx的;另一个疑问是调用的时候name()方法是怎么出来的,为什么能直接输出枚举值。

查看了java Enum源代码:

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
    /**
     * 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;

    /**
     * Returns the name of this enum constant, exactly as declared in its
     * enum declaration.
     *
     * <b>Most programmers should use the {@link #toString} method in
     * preference to this one, as the toString method may return
     * a more user-friendly name.</b>  This method is designed primarily for
     * use in specialized situations where correctness depends on getting the
     * exact name, which will not vary from release to release.
     *
     * @return the name of this enum constant
     */
    public final String name() {
        return name;
    }
}

可以看到name()方法和toString()方法几乎是一样的,可以实现字符串输出。

而枚举类Test首先是一个类,然后是枚举。

Test类中定义的SAT("sat")是根据Test类的构造方法建立的,因为@AllArgsConstructor注释没有将构造方法显式地定义出来。

实际的构造方法应该是这样的:

Test(String test){}

所以Test中定义的SAT的类型是Test,Test.SAT首先是一个Test实例,然后调用继承Enum中的name()方法。

枚举类更具体的文章可以参考深入理解Java枚举类型(enum)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值