Advanced enum Concepts
Advanced Enum Features in Java
Advanced Techniques for Iterating Over an enumThis excellent article: https://www.baeldung.com/java-enum-iteration describes several advanced techniques for iterating over an enum. Some of these techniques use functional programming which you will learn later in this course.
Defining Custom Values for enum Constants
In the following video, we learn how to override the default integer values assigned to our Enum constants.
Enums can contain constructors (but only private constructors), methods, variables, and constant class bodies. You can specify values of enum constants at the creation time as shown below. The programmer cannot set a custom integer for an enum value directly, but one can define overloaded constructors that can then assign arbitrary values to self-defined members of the enum class. Defining getters allows then access to those self-defined members. The internal integer can be obtained from an enum value using the public getValue() method, and the list of enum values of an enumeration type can be obtained in order using the .values() method.
MyEnum.values()returns an array of type MyEnum’s values.
When Are enums Created by the Java Virtual Machine?
Instances of enum in Java are created when any enum constants are first called or referenced in code. Because they are static, they are only created once and used throughout the run of the program.
More About enums
- An enum can be declared outside or inside a class, but NOT in a method.
- An enum declared outside a class must NOT be marked static, final , abstract, protected , or private. enum constructors can have arguments (see above), and can be overloaded.
- enum constructors can NEVER be invoked directly in code. These constructors are called automatically when an enum is initialized.
- an enum is a reference type, which means it behaves more like a class or an interface than a primitive. Thus, uninitialized enum variables start life with a null value.
- an enum can have abstract methods.
- An enum can implement one or more interfaces. When it does so, it must implement all the methods of the interfaces: