Java枚举和具有私有构造函数的类之间有什么区别? [英] What are the differences between a Java enum and a class with private constructor?
问题描述
我正在尝试了解Java枚举是如何工作的,而且我得出的结论与一个普通的Java类非常相似,它将其构造函数声明为private。
I was trying to understand how Java enum really works and I have come to the conclusion that is very similar to a normal Java class that has it's 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;
}
}
上面的代码和下面?
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
classes
- 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
fields - 枚举可用于
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)
大多数可以使用适当设计的类模拟,但枚举
只是使用这套特别理想的属性创建一个类非常简单。
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屋!