作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的代码中有以下字段:
private static final int NUM_NANOSECONDS_IN_MILLISECOND = 1000000;
有人告诉我,为了类型安全,我应该使用枚举。这不是我所熟悉的事情。但如果是这种情况,我不知道什么时候适合在字段上使用final关键字。
什么时候应该使用final关键字而不是枚举?
最佳答案
常量就是有名称的常量。枚举是具有值的文字常量。我解释一下...
考虑:
public final static int NORTH = 0;
public final static int SOUTH = 1;
public final static int EAST = 2;
public final static int WEST = 3;
和
public enum Direction {
NORTH, SOUTH, EAST, WEST
}
从可读性的角度来看,它看起来有点相同:
if(direction == NORTH)
或使用枚举:
if(direction == Direction.NORTH)
可能出错的地方是,使用最终常量,您也可以这样做
if(direction == 0)
现在,即使代码做了同样的事情,理解它也变得更加困难。对于枚举,你不能这样做,所以会出现问题。
类似地,当期望方向作为方法参数时:
最终静态:
public void myMethod(int direction)
以及枚举:
public void myMethod(Direction direction)
更清晰,出现问题的机会更少。
这只是一个开始。枚举实际上可以有一些方法来帮助您更好地管理它们包含的信息。阅读 here以获得清晰的解释。
示例:
public enum Direction {
NORTH (0, 1),
SOUTH (0, -1),
EAST (1, 0),
WEST (-1, 0)
private int xDirection, yDirection;
Direction(int x, int y) {
this.xDirection = x;
this.yDirection = y;
}
public Vector2D getTranslation() {
return new Vector2D(this.xDirection, this.yDirection);
}
}
那么在你的代码中:
public void moveThePlayer(Player p, Direction d) {
p.translate(d.getTranslation());
}
moveThePlayer(p, Direction.NORTH);
这对于final static
来说真的很难做到。或者至少,它变得非常难以阅读。
关于java - 什么时候应该使用final关键字而不是枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473760/
我是一名优秀的程序员,十分优秀!