views:

2950

answers:

6

Is there a way to write an enumeration that can be extended. I have several methods that I would like to alway 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;
       }
     }
+6  A: 

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

Guido
+4  A: 

If I understand correctly, what you'd like to do is something like this:

public abstract class DatabaseField {

  private String FieldName;

  private DatabaseField(String fname) {
    this.FieldName = fname;
  }

  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.

Don
+3  A: 

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

Guðmundur Bjarni
I think that's the most sensible design here right? If an enum implements the right interface then you know it is an enum of database fields.
Revah
A: 

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?

+2  A: 

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

Alex Miller
A: 

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.

Aidos