枚举与静态final

来源:互联网 发布:js代码中未定义变量 编辑:程序博客网 时间:2024/06/06 09:05

枚举由于静态final,因为前者比后者更安全。如下代码:

enum ShapeType{    RECTANGLE,TRIANGLE,OVAL}public class ExpTst {    public  ShapeType type;    public static void main(String[] args) {        ExpTst expTst=new ExpTst();        System.out.println(expTst.type);        expTst.type=ShapeType.RECTANGLE;        System.out.println(expTst.type);    }}

运行输出:

nullRECTANGLE

再看使用静态final的例子:

class ShapeType{    public static final int IVDIVDUAL=1;}public class ExpTst {    public  int type;    public static void main(String[] args) {        ExpTst expTst=new ExpTst();        System.out.println(expTst.type);        //正常情况下        //expTst.type=ShapeType.IVDIVDUAL;        expTst.type=5;        System.out.println(expTst.type);    }}

注意到此时type可以为一个意想不到的无效整数值。要想保证一个变量只能被赋予一个有效值,显然枚举相对较好。
另一个不同时,枚举值是一个对象,因为它的行为和对象一样。例如把他用作Map键。

0 0
原创粉丝点击