相关疑难解决方法(0)

你应该总是使用枚举而不是Java中的常量

在java <1.5中,常量将像这样实现

public class MyClass {
    public static int VERTICAL = 0;
    public static int HORIZONTAL = 1;

    private int orientation;

    public MyClass(int orientation) {
        this.orientation = orientation;
    }
...
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

MyClass myClass = new MyClass(MyClass.VERTICAL);
Run Code Online (Sandbox Code Playgroud)

现在,在1.5中显然你应该使用枚举:

public class MyClass {
    public static enum Orientation {
        VERTICAL, HORIZONTAL;
    }

    private Orientation orientation;

    public MyClass(Orientation orientation) {
        this.orientation = orientation;
    }
...
Run Code Online (Sandbox Code Playgroud)

现在你会像这样使用它:

MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
Run Code Online (Sandbox Code Playgroud)

我觉得有点难看.现在我可以轻松添加几个静态变量:

public class MyClass {
    public static Orientation VERTICAL = Orientation.VERTICAL;
    public static …
Run Code Online (Sandbox Code Playgroud)

java enums coding-style

12
推荐指数
3
解决办法
2万
查看次数

标签 统计

coding-style ×1

enums ×1

java ×1