title: Should you always use enums instead of constants in Java
body: <p>In java &lt;1.5, constants would be implemented like this</p>
  
  <pre><code>public class MyClass {
      public static int VERTICAL = 0;
      public static int HORIZONTAL = 1;
  
      private int orientation;
  
      public MyClass(int orientation) {
          this.orientation = orientation;
      }
  ...
  </code></pre>
  
  <p>and you would use it like this:</p>
  
  <pre><code>MyClass myClass = new MyClass(MyClass.VERTICAL);
  </code></pre>
  
  <p>Now, in 1.5 obviously you should be using enums:</p>
  
  <pre><code>public class MyClass {
      public static enum Orientation {
          VERTICAL, HORIZONTAL;
      }
  
      private Orientation orientation;
  
      public MyClass(Orientation orientation) {
          this.orientation = orientation;
      }
  ...
  </code></pre>
  
  <p>and now you would use it like this:</p>
  
  <pre><code>MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
  </code></pre>
  
  <p>Which I find slightly ugly. Now I could easily add a couple of static variables:</p>
  
  <pre><code>public class MyClass {
      public static Orientation VERTICAL = Orientation.VERTICAL;
      public static Orientation HORIZONTAL = Orientation.HORIZONTAL;
  
      public static enum Orientation {
          VERTICAL, HORIZONTAL;
      }
  
      private Orientation orientation;
  
      public MyClass(Orientation orientation) {
          this.orientation = orientation;
      }
  ...
  </code></pre>
  
  <p>And now I can do this again:</p>
  
  <pre><code>MyClass myClass = new MyClass(MyClass.VERTICAL);
  </code></pre>
  
  <p>With all the type-safe goodness of enums.</p>
  
  <p>Is this good style, bad style or neither. Can you think of a better solution?</p>
  
  <p><strong>Update</strong></p>
  
  <p>Vilx- was the first one to highlight what I feel I was missing - that the enum should be a first-class citizen. In java this means it gets its own file in the package - we don't have namespaces. I had thought this would be a bit heavyweight, but having actually done it, it definitely feels right.</p>
  
  <p>Yuval's answer is fine, but it didn't really emphasise the non-nested enum. Also, as for 1.4 - there are plenty of places in the JDK that use integers, and I was really looking for a way to evolve that sort of code.</p>