Java 16 Enhanced Enums (JEP 361)

Java 16 introduced enhanced enums, which are a new feature that allows you to add new methods and fields to enums, as well as implement interfaces and override methods. Enhanced enums are a useful way to extend the functionality of enums and to make them more flexible and powerful.

Here is an example of how to use enhanced enums in Java:

enum Color {
  RED, GREEN, BLUE;

  // New method
  public int getRGB() {
    switch (this) {
      case RED: return 0xFF0000;
      case GREEN: return 0x00FF00;
      case BLUE: return 0x0000FF;
      default: throw new AssertionError("Unknown color: " + this);
    }
  }
}

Color c = Color.RED;
int rgb = c.getRGB();  // 0xFF0000

In this example, we are defining an enum called Color that represents the primary colors. The enum has three values: RED, GREEN, and BLUE. We are also adding a new method called getRGB that returns the RGB value of the color. To use the method, we simply call it on the enum value, as if it were a regular method.

Enhanced enums can be used in a variety of contexts, such as in switch statements, try-with-resources blocks, and Lambda expressions. They can also be used to define constants, which are values that are fixed at compile time and cannot be changed at runtime.

One important thing to note about enhanced enums is that they are not suitable for all cases. In particular, they may not be suitable for cases where you need to add a large number of methods or fields to an enum, or where you need to define complex behavior that cannot be represented using a single method or field. In these cases, it may be more appropriate to use a regular class or an interface instead.