Java 枚举和具有私有构造函数的类有什么区别? [英] What are the differences between a Java enum and a class with private constructor?
问题描述
我试图了解 Java 枚举的真正工作原理,我得出的结论是,它与构造函数声明为私有的普通 Java 类非常相似.
I was trying to understand how Java enum really works and I have come to the conclusion that it is very similar to a normal Java class that has its constructor declared private.
我刚刚得出这个结论,并没有经过太多思考,但我想知道我是否遗漏了什么.
I have just come to this conclusion and it isn't based on much thinking, but Id like to know whether I miss anything.
下面是一个简单的 Java 枚举和一个等效的 Java 类的实现.
So below is an implementation of a simple Java enum and an equivalent Java class.
public enum Direction {
ENUM_UP(0, -1),
ENUM_DOWN(0, 1),
ENUM_RIGHT(1, 0),
ENUM_LEFT(-1, 0);
private int x;
private int y;
private Direction(int x, int y){
this.x = x;
this.y = y;
}
public int getEnumX(){
return x;
}
public int getEnumY(){
return y;
}
}
上面和下面的代码在含义上有什么区别?
What is the difference in meaning between the code above and below?
public class Direction{
public static final Direction UP = new Direction(0, -1) ;
public static final Direction DOWN = new Direction(0, 1) ;
public static final Direction LEFT = new Direction(-1, 0) ;
public static final Direction RIGHT = new Direction(1, 0) ;
private int x ;
private int y ;
private Direction(int x, int y){
this.x = x ;
this.y = y ;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
推荐答案
区别:
- 枚举扩展了
java.lang.Enum
并获得了它的所有 不错的功能:
- Enums extend
java.lang.Enum
and gain all of its nice features:
- 通过正确的序列化实现自动单例行为
- 自动对枚举值进行可读的
.toString
方法,无需复制枚举名称 .name
和.ordinal
特殊目的方法- 可用于基于位集的高性能
EnumSet
和EnumMap
类
- Automatic singleton behaviour through correct serialization
- Automatic human-readable
.toString
method on enum values without the need to duplicate your enum names .name
and.ordinal
special-purpose methods- Usable in high-performance bitset-based
EnumSet
andEnumMap
classes
- 枚举使用特殊的语法,无需编写数十个
public static final
字段即可简化实例的创建 - 枚举可用于
switch
语句 - 枚举不能在枚举列表之外实例化,除非使用反射
- 枚举不能扩展到枚举列表之外
- Enums use a special syntax which simplifies instance creation without writing dozens of
public static final
fields - Enums can be used in
switch
statements - Enums cannot be instantiated outside the enumeration list except by using reflection
- Enums cannot be extended outside the enumeration list
public static (Enum)[] values();
public static (Enum) valueOf(java.lang.String);
private static final (Enum)[] $VALUES;
(values()
返回一个副本)
public static (Enum)[] values();
public static (Enum) valueOf(java.lang.String);
private static final (Enum)[] $VALUES;
(values()
returns a clone of this)
其中大部分都可以通过适当设计的类来模拟,但是 Enum
只是让创建具有这组特别理想属性的类变得非常容易.
Most of these can be emulated with a suitably designed class, but Enum
just makes it really easy to create a class with this set of particularly desirable properties.
这篇关于Java 枚举和具有私有构造函数的类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!