java 枚举 final,Java枚举与具有公共静态final字段的类有什么优势?

I am very familiar with C# but starting to work more in Java. I expected to learn that enums in Java were basically equivalent to those in C# but apparently this is not the case. Initially I was excited to learn that Java enums could contain multiple pieces of data which seems very advantageous (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). However, since then I have found a lot of features missing that are trivial in C#, such as the ability to easily assign an enum element a certain value, and consequently the ability to convert an integer to an enum without a decent amount of effort (i.e. Convert integer value to matching Java Enum).

So my question is this: is there any benefit to Java enums over a class with a bunch of public static final fields? Or does it just provide more compact syntax?

EDIT: Let me be more clear. What is the benefit of Java enums over a class with a bunch of public static final fields of the same type? For example, in the planets example at the first link, what is the advantage of an enum over a class with these public constants:

public static final Planet MERCURY = new Planet(3.303e+23, 2.4397e6);

public static final Planet VENUS = new Planet(4.869e+24, 6.0518e6);

public static final Planet EARTH = new Planet(5.976e+24, 6.37814e6);

public static final Planet MARS = new Planet(6.421e+23, 3.3972e6);

public static final Planet JUPITER = new Planet(1.9e+27, 7.1492e7);

public static final Planet SATURN = new Planet(5.688e+26, 6.0268e7);

public static final Planet URANUS = new Planet(8.686e+25, 2.5559e7);

public static final Planet NEPTUNE = new Planet(1.024e+26, 2.4746e7);

As far as I can tell, casablanca's answer is the only one that satisfies this.

解决方案

Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值