Contents

Enum with properties using Java

Written by: David Vlijmincx

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public enum Vehicles {

    CAR("red"),
    BIKE("Blue"),
    BOAT("Yellow");

    private final String color;

    Vehicles(String color) {
        this.color = color;
    }

    public String getColor(){
        return this.color;
    }
}

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public enum Vehicles {

    CAR("red"),
    BIKE("Blue"),
    BOAT("Yellow"){
        @Override
        public String getColor() {
            return  "My color is: " + super.getColor();
        }
    };

    private final String color;

    Vehicles(String color) {
        this.color = color;
    }

    public String getColor(){
        return this.color;
    }
}

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.