Java Enum Basics
What is an Enum?
An enumeration (enum) in Java is a special type of class used to define a collection of constants. Enums provide a way to create a group of related constants with more type safety and clarity compared to traditional integer or string constants.
Defining an Enum
Here's a basic example of how to define an enum in Java:
public enum DaysOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Enum Characteristics
Enums in Java have several unique characteristics:
Feature |
Description |
Type Safety |
Enums provide compile-time type checking |
Singleton |
Each enum constant is a singleton instance |
Methods |
Enums can have methods, constructors, and fields |
Advanced Enum Definition
Enums can be more complex and include additional functionality:
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6);
private final double mass; // in kilograms
private final double radius; // in meters
// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// Method to calculate surface gravity
public double surfaceGravity() {
return G * mass / (radius * radius);
}
}
Enum Workflow
stateDiagram-v2
[*] --> Define
Define --> Initialize
Initialize --> Use
Use --> [*]
Key Benefits of Enums
- Type safety
- Improved code readability
- Ability to add methods and fields
- Built-in serialization
- Thread safety
When to Use Enums
Enums are particularly useful when you have a fixed set of constants that won't change, such as:
- Days of the week
- Months of the year
- Card suits
- Predefined status values
By leveraging enums, developers can create more robust and maintainable code in LabEx projects and beyond.