Overriding the toString() Method
By default, when you print an enum object or use it in a string context, the toString()
method of the enum is called, which returns the name of the enum constant as a String
. However, you can override the toString()
method to provide a custom string representation for your enum.
Here's an example of overriding the toString()
method in a DayOfWeek
enum:
public enum DayOfWeek {
MONDAY("Monday"),
TUESDAY("Tuesday"),
WEDNESDAY("Wednesday"),
THURSDAY("Thursday"),
FRIDAY("Friday"),
SATURDAY("Saturday"),
SUNDAY("Sunday");
private final String displayName;
DayOfWeek(String displayName) {
this.displayName = displayName;
}
@Override
public String toString() {
return displayName;
}
}
In this example, each enum constant has a private displayName
field that stores the custom string representation for that constant. The toString()
method is overridden to return the displayName
value instead of the default enum name.
Now, when you use the DayOfWeek
enum in your code, the custom string representation will be used:
DayOfWeek today = DayOfWeek.MONDAY;
System.out.println(today); // Output: Monday
Overriding the toString()
method can be particularly useful when you want to provide a more user-friendly or descriptive representation of your enum constants. This can make your code more readable and easier to understand, especially when working with enums in user interfaces or logging/debugging scenarios.
Here's another example of overriding the toString()
method in a Color
enum:
public enum Color {
RED("Red", 255, 0, 0),
GREEN("Green", 0, 255, 0),
BLUE("Blue", 0, 0, 255);
private final String name;
private final int red;
private final int green;
private final int blue;
Color(String name, int red, int green, int blue) {
this.name = name;
this.red = red;
this.green = green;
this.blue = blue;
}
@Override
public String toString() {
return name;
}
// Other methods to get color properties
}
In this example, the Color
enum has a name
field that stores the custom string representation for each color. The toString()
method is overridden to return the name
value instead of the default enum name.
Overriding the toString()
method in your enums can greatly improve the readability and usability of your code, especially when working with enums in various contexts.