Java - Implement the interface method in the enum type body

Introduction

The following code shows another way to implement interface in enum.

It implements the interface method in the enum type body

In this way you can omit the implementations from some or all enum constants.

Demo

interface Command {
  void execute();
}

enum CommandList implements Command {
  RUN,  JUMP;// w  w w .  j a v a 2  s .  c o  m


  public void execute(){
    System.out.println("Command:"+super.name());
  }
}

public class Main {
  public static void main(String... args) {
    // Execute all commands in the command list
    for (Command cmd : CommandList.values()) {
      cmd.execute();
    }
  }
}

Result

Related Topic