Java - Enum Type Implementing Interface

Introduction

An enum type may implement interfaces.

An enum type is never inherited by another enum type.

You cannot declare an enum type as abstract.

If an enum type implements an interface, it must also provide implementation for all abstract methods from the interface.

Example

The following code declares a Command interface.

interface Command {
        void execute();
}

Then it declares an enum type called CommandList that implements the Command interface.

Each enum constant implements the execute() method of the Command interface.

Demo

interface Command {
  void execute();
}

enum CommandList implements Command {
  RUN {//from  w w  w . j  a  v  a2  s  .  c  o m
    public void execute() {
      System.out.println("Running...");
    }
  },
  JUMP {
    public void execute() {
      System.out.println("Jumping...");
    }
  };

  // Force all constants to implement the execute() method.
  public abstract void execute();
}

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 Topics