Java enumeration, how and when allocated memory for constant

I have a simple enum class as below. I want to know how memory is allocated for each constant (an object of a member class 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; } } 
+6
source share
2 answers

Elements HAPPY("HAPPY"),RAhul("RAhul"),ANSAL("ANSAL"); are created when the enumeration class is loaded (i.e., their scope is static). Enumerations are compiled into regular classes that extend java.lang.Enum , and its instances are allocated on the heap, like other class objects.

Each member invokes a constructor, which is defined in the enumeration, which takes a string parameter.

This is from the corresponding section in the Java Language Specification :

The enumeration constant can be followed by arguments that are passed to the constructor of the enum type when the constant is created during class initialization, as described later in this section. The called constructor is selected using the normal overload rules (ยง15.12.2). If arguments are omitted, an empty argument list is assumed.

+5
source

For all practical purposes, java considers enum as a class that can have only a fixed number of objects (an object corresponding to each enumeration constant). Thus, an enumeration is basically an action similar to a class when loading, initializing, etc.

0
source

Source: https://habr.com/ru/post/981015/


All Articles