# 可以将枚举用作类吗？

go评论27阅读模式

Could an enum be used as a class?

# 问题

``````public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS   (4.869e+24, 6.0518e6),
EARTH   (5.976e+24, 6.37814e6),
MARS    (6.421e+23, 3.3972e6),
JUPITER (1.9e+27,   7.1492e7),
SATURN  (5.688e+26, 6.0268e7),
URANUS  (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);

private final double mass;   // 千克
private final double radius; // 米
this.mass = mass;
}
private double mass() { return mass; }

// 通用引力常数 (m3 kg-1 s-2)
public static final double G = 6.67300E-11;

double surfaceGravity() {
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
``````

I was reading through the Java Oracle Tutorials, and I saw an example of enum in use:

``````
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS   (4.869e+24, 6.0518e6),
EARTH   (5.976e+24, 6.37814e6),
MARS    (6.421e+23, 3.3972e6),
JUPITER (1.9e+27,   7.1492e7),
SATURN  (5.688e+26, 6.0268e7),
URANUS  (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass;   // in kilograms
private final double radius; // in meters
this.mass = mass;
}
private double mass() { return mass; }
// universal gravitational constant  (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println(&quot;Usage: java Planet &lt;earth_weight&gt;&quot;);
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf(&quot;Your weight on %s is %f%n&quot;,
p, p.surfaceWeight(mass));
}
}
``````

I always thought that enums were sets of related constants that were usually used outside of a class, but this example shows enum being used as if it was a class, with its own methods and constructors. I know that it is an enum because of the "enum" in the class declaration. Could an enum be used like a class? What is the difference between a class and an enum if they are this similar? What are some good uses for enums that act like a standard class?

Thanks

# 答案1

• 拥有实例字段，这些字段可以是 final 的，也可以不是（虽然在常规用法中它们是不可变的，但这不是必需的）
• 拥有类（`static`）字段（尽管它们必须在实例之后声明）
• 为字段拥有 getter/setter
• 拥有构造函数（只是不能是公共的）
• 实现接口
• 被注解装饰

An `enum` is very like a normal class, except that instances are defined at compile time and are guaranteed to be singletons, and they may not `extend` anything.

However, they can:

• have instance fields, that may be final or not (although in conventional usage they are immutable, it is not required)
• have class (`static`) fields (although they must be declared after the instances)
• have getters/setters for fields
• have constructors (just not public ones)
• implement interfaces
• be decorated with annotations

# 答案2

The `enum` keyword is a language construct that essentially creates a (final) class which extends `java.lang.Enum` and forces you to define the (possibly empty) set of all named instances upfront, inside the enum definition.
So the answer is definitely yes; actually, you can't really use it in any other way.

Even if you don't add any logic to it, it will still be class:

``````enum Day { SUNDAY, MONDAY... }
``````

This already provides you with static methods like `Day.valueOf()` and instance methods such as like `Day.SUNDAY.ordinal()`, `name()` or `compareTo()`.

The `enum` keyword is a language construct that essentially creates a (final) class which extends `java.lang.Enum` and forces you to define the (possibly empty) set of all named instances upfront, inside the enum definition.
So the answer is definitely yes; actually, you can't really use it in any other way.

Even if you don't add any logic to it, it will still be class:

``````enum Day { SUNDAY, MONDAY... }
``````

This already provides you with static methods like `Day.valueOf()` and instance methods such as like `Day.SUNDAY.ordinal()`, `name()` or `compareTo()`.

# 答案3

``````如果你想将枚举作为一个类来使用，可以按照以下方式使用。

public class Weather {

public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
private final Season season;

private static final List<Weather> listWeather = new ArrayList<Weather>();

private Weather(Season season) {
this.season = season;
}

public Season getSeason() {
return season;
}

static {

for (Season season: Season.values()) {
}
}

public static ArrayList<Weather> getWeatherList() {
return listWeather;
}
public String toString() {
return season.toString();
}
}
``````

If you want to use enum as a class, you can use it in below way.

``````public class Weather {
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
private final Season season;
private static final List &lt; Weather &gt; listWeather = new ArrayList &lt; Weather &gt; ();
private Weather(Season season) {
this.season = season;
}
public Season getSeason() {
return season;
}
static {
for (Season season: Season.values()) {
}
}
public static ArrayList &lt; Weather &gt; getWeatherList() {
return listWeather;
}
public String toString() {
return season;
}
}
``````

# 答案4

The main difference between an enum and a standard class is in the restrictions: All instances of an enum must be declared at compile time; all fields must be final and the class cannot be extended.

• 本文由 发表于 2020年8月3日 16:03:39
• 转载请务必保留本文链接：https://go.coder-hub.com/63225781.html
• java

go 26

go 29

go 31

go 31