Question

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;
                }
        } 
Was it helpful?

Solution

If I understand correctly, what you'd like to do 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 enum cannot extend a class, but it can implement an interface, so the best you can do at the moment is define an interface which includes the getFieldName() method and have all your enums implement this interface.

However, this means that you'll have to duplicate the implementation of this method (and any others) in all your enums. There are some suggestions in this question about ways to minimise this duplication.

OTHER TIPS

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

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

Abstract enums are potentially very useful (and currently not allowed). But a proposal and prototype exists if you'd like to lobby someone in 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

For a throwback to the pre-Java 5 days, take a look at Item 21, Chapter 5,Effective Java by Josh Bloch. He talks about extending "enums" by adding values, but perhaps you could use some of the techniques to add a new method?

Hand craft the enum in a mechanism similar to that defined in Josh Bloch's Effective Java.

I would add that if you need to "extend" the enum, then perhaps an enum isn't the construct you are after. They are meant to be static constants IMHO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top