Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enums - choice between fields, abstract methods, and class level map

Tags:

java

oop

enums

I have written a Java enum where the values have various attributes. These attributes could be stored in any of the following ways:

Using fields:

enum Eenum {
  V1(p1),
  V2(p2);

  private final A attr;

  public A attr() { return attr; }

  private Eenum(A attr) {
    this.attr = attr;
  }
}

Using abstract methods:

enum Eenum {
  V1 {
    public A attr() { return p1; }
  },

  V2 {
    public A attr() { return p2; }
  }

  public abstract A attr();
}

Using class level map:

enum Eenum {
  V1,
  V2;

  public A attr() { return attrs.get(this); }

  private static final Map<Eenum, A> attrs;

  static {
    ImmutableMap.Builder<Eenum, A> builder = ImmutableMap.builder();
    builder.put(V1, p1);
    builder.put(V2, p2);
    attrs = builder.build();
  }
}

How should I decide when to prefer which?

Thanks!

like image 623
missingfaktor Avatar asked Nov 01 '12 18:11

missingfaktor


People also ask

Can you use abstract methods in enum?

Yes, you can define abstract methods in an enum declaration if and only if all enum values have custom class bodies with implementations of those methods (i.e. no concrete enum value may be lacking an implementation).

Can enums be abstract?

Enums can define abstract methods, which each enum member is required to implement. This allows for each enum member to define its own behaviour for a given operation, without having to switch on types in a method in the top-level definition.

Can enum extend abstract class?

Can Enum extend a class in java? Enum cannot extend any class in java,the reason is, by default Enum extends abstract base class java.

Which class does all the enums extend?

Which class does all the Enums extend? Explanation: All enums implicitly extend java. lang. Enum.


1 Answers

I would do the one which you think is the simplest.

In general I don't write code which can be implemented using data. I would use the first one.

My actual use case has some attributes which are not relevant for all enum values

You can use a combination of these approaches if it makes sense on a per attribute basis.

A fourth option is to not have an abstract method.

enum Eenum {
  V1 {
    public A attr() { return p1; }
  },

  V2 {
    public A attr() { return p2; }
  }, 
  V3, V4, V5, V6;

  public A attr() { return defaultA; }
}
like image 73
Peter Lawrey Avatar answered Nov 02 '22 00:11

Peter Lawrey