public class MyClass {
public static int VERTICAL = 0;
public static int HORIZONTAL = 1;
private int orientation;
public MyClass(int orientation) {
this.orientation = orientation;
}
...
你可以像这样使用它:
MyClass myClass = new MyClass(MyClass.VERTICAL);
现在,在1.5版本中,显然应该使用枚举类型:
public class MyClass {
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
现在您可以像这样使用它:
MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
我觉得这有点丑陋。现在,我可以轻松地添加一对静态变量:
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;
}
...
现在我又可以这样做了:
MyClass myClass = new MyClass(MyClass.VERTICAL);
具备枚举类型安全的优点。
这是好的风格、坏的风格还是都不是?你能想到更好的解决方案吗?
更新
Vilx- 是第一个强调我感觉遗漏的部分——枚举应该是一等公民。在Java中,这意味着它在包中有自己的文件——我们没有命名空间。我曾认为这可能有些繁重,但实际上这样做肯定是正确的。
Yuval 的回答很好,但它没有真正强调非嵌套枚举。此外,对于1.4来说,在JDK中有很多地方使用整数,我真的在寻找一种使这种代码得以演变的方法。