Introduction
This post covers how to add a field to an enum. We will also cover how you can override an enum method.
Adding a field to an enum
In the following example, I created an enum type of Vehicles. Each vehicle in the Vehicles enum has a different color that is passed to it by calling the constructor. When calling getColor on one of the enum types will return the color that belongs to that vehicle.
|
|
Notice that the list of different types now ends with a ;
instead of an empty line or ,
. This is done because want to add more to
this enum than just the types. I also needed to add a field, a constructor, and a getter method.
Override an enum method
You can also override a method inside an enum. In the following example, BOAT overrides the getColor() method and adds text to the return value.
|
|
On line 6 the getColor method is overridden. When you call Vehicles.BOAT.getColor() it will return “My color is: Yellow” instead of “Yellow”.
Conclusion
In this post, we learned how to add fields to an enum and how to override a method inside an enum.