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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.