Advertisement
Google Ad Slot: content-top
Java Enum
In Java, an enum is a special data type that represents a group of constants (unchangeable variables). Enums are used when you have a fixed set of predefined values, such as directions (NORTH, SOUTH, EAST, WEST), days of the week, or months.
Key Points About Enums in Java:
- Defined Using
enumKeyword:
- An enum is a distinct data type and is declared using the
enumkeyword.
- Implicit Features:
- Enums are implicitly static and final.
- Enum constants are implicitly public, static, and final.
- Enum in a Class:
- Enums can be declared inside or outside a class but not inside a method.
- Enum With Methods:
- Enums can include fields, constructors, and methods.
- Enum Cannot Extend Classes:
- Since enums implicitly extend
java.lang.Enum, they cannot extend any other class.
Syntax:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
Example 1: Basic Enum
Example 2: Iterating Through Enums:
You can use the values() method to iterate over all the constants of an enum.
Example 3: Enum With Fields and Methods:
Enums can have fields, constructors, and methods. Enum constants can also behave like objects.
Example 4: Enum With Switch Case
Example 5: Enum With Abstract Methods:
Enums can have abstract methods, and each constant must provide an implementation for it.