把常量定义在接口里与类里都能通过编译,那2者到底有什么区别呢?
那个更合理?
public interface ConstInterfaceA { public static final String CONST_A = "aa"; public static final String CONST_C = "cc"; }
存在问题:
==
对比, 只能用 equals
对比, 不能优化性能public class ConstClassA { public static final String CONST_A = "aa"; public static final String CONST_C = "cc"; private ConstClassA() { } }
private
public class EnumClassA { private String name; private EnumClassA(String name) { this.name = name; } public static final EnumClassA CONST_A = new EnumClassA("aa"); public static final EnumClassA CONST_C = new EnumClassA("cc"); }
解决了以上所有问题, 主要体现在:
EnumClassA
类型, 这样就转变成了强类型, 不会出现弱类型引起的问题==
直接对比, 性能会有提高public static enum Grade { A(4), B(3), C(2), D(1), F(0); private int points; Grade(int points) { this.points = points; } int getPoints() { return points; } };
JDK 1.5
引入的, 其实就是枚举常量类的代码封装简化而已