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 ww .  j  a  va2s. c om*/


  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