I have multiple enum types, a typical implementation is as follows.
public enum SomeType {
TYPE_A("aaa"),
TYPE_B("bbb"),
private final String type;
private SomeType(String type) { this.type = type; }
public boolean equals(String otherType) {
return (otherType == null) ? false : type.equals(otherType.toUpperCase());
}
}
Other than specific enum types, the constructor and methods (i.e., equals and a few more) are the same for these enums. I cant create a super "class" and extends from it. Is there a clean solution so that I only need 1 copy of these methods and make all enum types inherit them? Thanks.
Enum types are permitted to implement interfaces, like any other class. An example in Java SE is StandardCopyOption and LinkOption, which both implement CopyOption.
Although CopyOption doesn't have any methods, you certainly can define methods in such an inherited interface if you wish.
public interface TypedValue {
String getType();
default boolean equals(String otherType) {
return otherType != null && getType().equals(otherType.toUpperCase());
}
}
public enum SomeType
implements TypedValue {
TYPE_A("aaa"),
TYPE_B("bbb");
private final String type;
private SomeType(String type) { this.type = type; }
@Override
public String getType() {
return type;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With