Enum Constants Override Abstract Methods

Give each enum constant its own behavior via an abstract method in the enum body, overridden per constant, so a new command cannot miss its implementation.

JavaCli Tooling

Code

snippet
public class CommandRouter {

    enum Command {
        // Each constant overrides its own implementation: adding a command means adding one constant
        START {
            @Override
            String execute(String arg) {
                return "started with " + arg;
            }
        },
        STOP {
            @Override
            String execute(String arg) {
                return "stopped after " + arg;
            }
        },
        STATUS {
            @Override
            String execute(String arg) {
                return arg == null ? "idle" : "busy with " + arg;
            }
        };

        // The abstract method forces every constant to supply behavior; a missing override fails compilation
        abstract String execute(String arg);
    }

    public static void main(String[] args) {
        for (Command cmd : Command.values()) {
            System.out.println(cmd.name().toLowerCase() + " -> " + cmd.execute("job-7"));
        }
        System.out.println("status(null): " + Command.STATUS.execute(null));
    }
}

How it works

Enum Constants Override Abstract Methods comes down to the classes CommandRouter and Command and the function main.

Repetition is confined to for (Command cmd : Command.values()) — the rest of the file is straight-line.

Points of care

  • Runs with what the toolchain already gives you — nothing extra.

Putting it to use

The primary signature is public static void main(String[] args)

Output lines are prefixed (status(null):), which keeps every step answerable in the printed output.

Core lines

return arg == null ? "idle" : "busy with " + arg;
return "stopped after " + arg;
return "started with " + arg;

Interactive Tools for This Topic

FAQ

What does Enum Constants Override Abstract Methods print when run?
Invoke the file as-is — the `status(null):` prefixes identify which step printed each line.