Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database.
public enum ORDERFIELDS
{
OrderID("Order_ID");
private String FieldName;
private ORDERFIELDS(String fname)
{
this.FieldName = fname;
}
public String getFieldName()
{
return FieldName;
}
}
Show activity on this post. Show activity on this post. You cannot make Enums extend other Enums, but you can declare an interface which all your Enums can implement. The interface will have to include any methods you expect to invoke on your Enum values. Here is an example:
When we want to extend a Java class, we'll typically create a subclass. In Java, enums are classes as well. In this section, let's see if we can inherit an enum as we do with regular Java classes. 2.1. Extending an Enum Type First of all, let's have a look at an example so that we can understand the problem quickly:
The enum type has a values () method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum: An enum can, just like a class, have attributes and methods.
However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code. The methods declared by Enumeration are summarized in the following table −
All enums implicitly extend java.lang.Enum
. Since Java does not support multiple inheritance, an enum cannot extend anything else.
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