In java <1.5, constants would be implemented like this
public class MyClass {
public static int VERTICAL = 0;
public static int HORIZONTAL = 1;
private int orientation;
public MyClass(int orientation) {
this.orientation = orientation;
}
...
and you would use it like this:
MyClass myClass = new MyClass(MyClass.VERTICAL);
Now, in 1.5 obviously you should be using enums:
public class MyClass {
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
and now you would use it like this:
MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
Which I find slightly ugly. Now I could easily add a couple of static variables:
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;
}
...
And now I can do this again:
MyClass myClass = new MyClass(MyClass.VERTICAL);
With all the type-safe goodness of enums.
Is this good style, bad style or neither. Can you think of a better solution?
Update
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.
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.