In Apex, you can define your custom enumerations, also known as user-defined enums.
User-defined enums allow you to create your own sets of symbolic constants with meaningful names,
making your code more readable and self-explanatory. Here's how you can define and use
a user-defined enum in Apex:
public class EnumExample {
// Define a user-defined enumeration for Days of the Week
public enum DayOfWeek {
MONDAY('Monday'),
TUESDAY('Tuesday'),
WEDNESDAY('Wednesday'),
THURSDAY('Thursday'),
FRIDAY('Friday'),
SATURDAY('Saturday'),
SUNDAY('Sunday');
private String label; // A field to store a user-friendly label for each value
// Constructor for the enum values
DayOfWeek(String label) {
this.label = label;
}
// Getter method for the label
public String getLabel() {
return label;
}
}
public static void main() {
// Access the user-defined enum values
DayOfWeek today = DayOfWeek.WEDNESDAY;
// Use the enum values in conditional logic and display labels
System.debug('Today is ' + today);
System.debug('Today is ' + today.getLabel());
if (today == DayOfWeek.WEDNESDAY) {
System.debug('It\'s Wednesday!');
} else {
System.debug('It\'s not Wednesday.');
}
}
}
We define a user-defined enumeration DayOfWeek to represent the days of the week. For each day, we provide a label that describes the day.
We define a constructor within the enum to set the label for each enum value.
We provide a getter method, getLabel(), to access the label for each enum value.
In the main method, we access and use the enum values. We also call the getLabel method to retrieve the user-friendly label associated with the enum value.
We use the enum values in conditional logic and print messages based on the day.