Java extension with extension

Is there a way to write an enumeration that can be extended. I have several methods that I would always like to have for my listings. For example, I use enumeration for the fields of my database. I am including 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; } } 
+7
java enums design-patterns enumeration
source share
6 answers

If I understand correctly what you want to do, it is something like this:

 public abstract class DatabaseField { private String fieldName; private DatabaseField(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return fieldName; } } 

Then define your enum to extend this class. However, unfortunately, an enumeration cannot extend the class, but it can implement an interface, so the best thing at the moment is to define an interface that includes the getFieldName () method, and all your enums implement this interface.

However, this means that you will have to duplicate the implementation of this method (and any others) in all of your enumerations. There are several suggestions in this question about ways to minimize this duplication.

+10
source share

All enums implicitly extend java.lang.Enum . Since Java does not support multiple inheritance, an enumeration cannot propagate anything.

+16
source share

Enums can implement interfaces, but not extend, because when compiled they translate to java.lang.Enum.

+6
source share

Abstract enumerations are potentially very useful (and not currently permitted). But a proposal and a prototype exist if you want to lobby someone at Sun to add it:

http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html

Sun RFE:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570766

+6
source share

To return to pre-Java 5 days, see Clause 21, Chapter 5, Effective Java by Josh Bloch . He talks about expanding "enumerations" by adding values, but maybe you could use some of the methods to add a new method?

0
source share

Hand create an enumeration in a mechanism similar to that described in Josh Bloch Effective Java.

I would add that if you need to "expand" an enumeration, then perhaps the enumeration is not the construct you are using. They are intended for IMHO static constants.

0
source share

All Articles