'Duplicate code across enums .. is there an approach to centralize common code in these enums?

I have the following 3 enum's in my project, which are all very similar.

Since each enum has at least 2 common fields i.e key and code, is there any way that I can make the common:

  • constructors
  • getters
  • field declarations

shared to all of my enums? Without having to declare inside each one.

I know no extends clause allowed for enum.

But is there an elegant way to achieve reuse of the common parts of these enums?

public enum CarType {

  SEAT("2000", "001"),
  FIAT("3000", "002");

  String key;

  String code;

  CarType(String key, String code) {
    this.key = key;
    this.code = code;
  }

  public String getKey() {
    return key;
  }
  public String getCode() {
    return code;
  }
}

public enum TruckType {

  MERCEDES("4000", "001"),
  FORD("5000", "002");

  String key;

  String code;

  TruckType(String key, String code) {
    this.key = key;
    this.code = code;
  }

  public String getKey() {
    return key;
  }
  public String getCode() {
    return code;
  }
}

public enum VanType {

  JEEP("6000", "001", "40"),
  KIA("7000", "002", "50");

  String key;

  String code;

  String tankSize;

  VanType(String key, String code, String tankSize) {
    this.key = key;
    this.code = code;
    this.tankSize = tankSize;
  }

  public String getKey() {
    return key;
  }
  public String getCode() {
    return code;
  }
  public String getTankSize() {
    return tankSize;
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source