可以将枚举用作类吗?

huangapple go评论27阅读模式
英文:

Could an enum be used as a class?

问题

我正在阅读Java Oracle教程,我看到了一个枚举(enum)的示例:

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; // 米
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

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

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    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));
    }
}

我一直以为枚举(enum)是一组相关的常量,通常在类外部使用,但这个示例中枚举被用得像是一个类,具有自己的方法和构造函数。我知道这是一个枚举,因为在类声明中有"enum"关键字。枚举是否可以像类一样使用?如果它们如此相似,类和枚举之间有什么区别?有哪些枚举行为类似标准类的好用途?

谢谢。

英文:

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
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant  (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
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

得分: 2

一个 enum 很像一个普通的类,除了实例在编译时定义并保证是单例的,它们不能 extend 任何东西。

然而,它们可以:

  • 拥有实例字段,这些字段可以是 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

得分: 1

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

得分: 0

以下是翻译好的部分:

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

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()) {
            listWeather.add(new Weather(season));
        }
    }

    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()) {
listWeather.add(new Weather(season));
}
}
public static ArrayList &lt; Weather &gt; getWeatherList() {
return listWeather;
}
public String toString() {
return season;
}
}

答案4

得分: -1

枚举和标准类之间的主要区别在于限制:枚举的所有实例必须在编译时声明;所有字段必须是final,并且不能扩展该类。

英文:

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.

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定