DEV Community

Duchet Loïc for Zenika

Posted on

Enums’ inheritance

Did you ever try to implement enums which are children of other ones ? In Java, you can’t do so. Enums can’t inherit, however you can use a simple tip to avoid this issue : composition.

First of all, create a list of all the elements you need. In our example, we will use a list of animals. Each of these animals are part of the same enumeration, so they share the same type and the same structure. For visibility, we will keep our example as simple as possible.

enum Animal {
  DOG,
  CAT,
  COW,
  ANT,
  BUTTERFLY,
  LADYBUG
}
Enter fullscreen mode Exit fullscreen mode

Then we create a “parent“ enum regrouping animals by type.

import static Animal;

enum AnimalType {
  MAMMAL(DOG, CAT, COW),
  INSECT(ANT, BUTTERFLY, LADYBUG);

  private List<Animal> animals;

  public AnimalType(Animal... animals) {
    this.animals = Arrays.asList(animals);
  }

  public List<Animal> getAnimals(){
    return animals;
  }
}
Enter fullscreen mode Exit fullscreen mode

This parent enumeration can be more complex. I recommend setting the list of elements at the end of parameters to gain visibility.

import static Animal;

enum ComplexAnimalType {
  MAMMAL(1, 2, Arrays.asList(DOG, CAT, COW)),
  INSECT(3, 4, Arrays.asList(ANT, BUTTERFLY, LADYBUG));

  private int field1;
  private int field2;
  private List<Animal> animals;

  public ComplexAnimalType(int field1,
                           int field2, 
                           List<Animal> animals) {
    this.field1 = field1;
    this.field2 = field2;
    this.animals = animals;
  }

  //getters
}
Enter fullscreen mode Exit fullscreen mode

Moreover, you can add tests which flatmap all animals from AnimalType to compare with the list of whole animals. This way, you will avoid mistakes like duplication or missing elements.

Top comments (0)