Explain Codes LogoExplain Codes Logo

Can enums be subclassed to add new elements?

java
enum-inheritance
best-practices
design-patterns
Anton ShumikhinbyAnton ShumikhinΒ·Sep 13, 2024
⚑TLDR

In Java, enums are implicitly final thereby making them extend-proof. However, you can emulate extensible enums using an interface and having multiple enums implement it.

public interface MutualFun { void incubate(); } public enum CryptoCurrency implements MutualFun { BITCOIN, ETHEREUM; @Override public void incubate() { // "Ethereum to the moon!" πŸš€πŸŒ• } } public enum PreciousMetal implements MutualFun { GOLD, SILVER; @Override public void incubate() { // "Don't just hold, treasure it." πŸ’°πŸ’² } }

This approach combines grouping and operational consistency while complying with Java's enum restrictions.

Interface and Enum cohesion

Extend Enums: Behaviorally

Enums can bundle behaviors related to every unique constant. This reduces the need for lengthy switch-case or if-else constructs in your code. Ahh, the sweet aroma of clean code.

public enum Status { WORKING { public void progress() { // "Just another day at the salt mines." } }, BROKEN { public void progress() { // "I've fallen and I can't get up!" } }; public abstract void progress(); }

Enums with utility methods

If you need to find an enum constant based on a string, valueOf(String) is your go-to method. In cases of extended enums, provide your utility methods to make interactions with enum collections more seamless.

public interface Identity { String getId(); static <E extends Enum<E> & Identity> E match(Class<E> enumClass, String id) { for (E constant : enumClass.getEnumConstants()) { if (constant.getId().equals(id)) return constant; } throw new IllegalArgumentException("Who are you again?"); } }

Can Enums be Subclassed to Add New Elements?

Conceptualize our enum as a locked treasure chest (πŸ”’πŸ§°):

Enum SafetyVault = πŸ”’πŸ§°: [πŸ΄β€β˜ οΈ, πŸ”‘, πŸ’Ž]

Adding new items to the locked chest:

Subclass Effort = πŸ› οΈπŸ”’πŸ§°+🌟

Regrettably...

Result: βŒπŸ”’πŸ§° (The lock remains, new items cannot be added)

Java enums are sealed for modification to safeguard their integrity and achieve consistency.

Aggregation of enums

Sometimes, instead of subclassing, you may want to assemble elements of various enums into a single unified enum. This stratagem simplifies decision making in the program, offering a complete set of prospects in a single construct.

Non-Enum Alternatives

When you don't require enum inheritance, peek at other class structures. If you don't need type-checking and comparison from java.lang.Enum itself, a class hierarchy with constants and behavior can be a potent replacement:

public abstract class Deliverable { public static final Deliverable PIZZA = new Deliverable() { @Override public void carry() { /* "Did someone order a pizza?" πŸ• */ } }; public static final Deliverable PARCEL = new Deliverable() { @Override public void carry() { /* "Parcel to your doorstep" πŸ“¦ */ } }; public abstract void carry(); }

Enums for Processing Contexts

Enums can streamline logic and group processes into common tasks under an explicit context. They conveniently encapsulate decision-making logic based on the object's state or type, leading to a tidy, well-managed codebase:

public enum OrderStatus { PROCESSING, DELIVERED, CANCELLED; // Let the enum dictate the order's destiny. }