[英]Java enum, how and when memory allocated per constant
I have simple enum class as given below. 我有简单的枚举类,如下所示。 i want to know how memory is allocated to each constant( is Member class object is created for each constant) and what is its scope.
我想知道如何为每个常量分配内存(为每个常量创建成员类对象)以及它的范围是什么。
public enum Member {
HAPPY("HAPPY"),RAhul("RAhul"),ANSAL("ANSAL");
private String argument;
Member(String arguments)
{
System.out.println("Enum Constructor work");
this.argument = arguments;
}
public String getValue() {
return argument;
}
}
The members HAPPY("HAPPY"),RAhul("RAhul"),ANSAL("ANSAL");
成员
HAPPY("HAPPY"),RAhul("RAhul"),ANSAL("ANSAL");
are created when the enum class is loaded (ie their scope is static). 在加载枚举类时创建(即它们的作用域是静态的)。 Enums are compiled to normal classes that extend
java.lang.Enum
and its instances are allocated in the heap like other class objects. 枚举被编译为扩展
java.lang.Enum
普通类,并且其实例像其他类对象一样在堆中分配。
Each member invokes the constructor that's defined in the enum which takes the string parameter. 每个成员调用在枚举中定义的构造函数,该构造函数接受字符串参数。
This is from the relevant section in the Java Language Specification : 这来自Java语言规范的相关部分 :
An enum constant may be followed by arguments, which are passed to the constructor of the enum type when the constant is created during class initialization as described later in this section.
枚举常量后面可以跟参数,当在类初始化期间创建常量时,这些参数将传递给枚举类型的构造函数,如本节后面所述。 The constructor to be invoked is chosen using the normal overloading rules (§15.12.2).
使用正常的重载规则(第15.12.2节)选择要调用的构造函数。 If the arguments are omitted, an empty argument list is assumed.
如果省略参数,则假定为空参数列表。
For all practical purposes, java considers enum as a class which can only has fixed number of Objects (an object corresponding to each enum constant defined). 出于所有实际目的,java将枚举视为一个只能具有固定数量的对象(对应于定义的每个枚举常量的对象)的类。 So enum is pretty much acts like a class in loading, initializing etc.
所以enum在加载,初始化等方面几乎就像一个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.