creating an enum/final class in java

Hristo picture Hristo · Jul 14, 2011 · Viewed 9.4k times · Source

I'm trying to figure out the best way to create a class whose sole purpose is to be a container for global static variables. Here's some pseudocode for a simple example of what I mean...

public class Symbols {
   public static final String ALPHA = "alpha";
   public static final String BETA = "beta";

   /* ...and so on for a bunch of these */
}

I don't need constructors or methods. I just need to be able to access these "symbols" from everywhere simply by calling: Symbols.ALPHA;

I DO need the actual value of the String, so I can't use an enum type. What would be the best way to accomplish this?

Answer

Jon Skeet picture Jon Skeet · Jul 14, 2011

Well, it's not clear what else you need beyond the code you've already given - other than maybe making the class final and giving it a private constructor.

However, in order to avoid accidentally using an inappropriate value, I suspect you would be better off making this an enum, like this:

public enum Symbol {
   ALPHA("alpha"),
   BETA("beta");

   private final String value;

   private Symbol(String value) {
     this.value = value;
   }

   public String getValue() {
     return value;
   }
}

That way:

  • You can't accidentally use Symbol.ALPHA where you're really just expecting a string
  • You can't accidentally use a string where you're really expecting a symbol
  • You can still easily get the string value associated with a symbol
  • You can switch on the different symbol values if you need to