Java常量放在Class还是Interface?

来源:互联网 发布:windows10优化设置 编辑:程序博客网 时间:2024/05/07 23:45

overview

之前习惯性把常量定义在interface中, 因为可以少写很多遍的 “public static final”, 但是近来浏览业务代码, 发现很多代码还是坚持将常量定义在class中, 因此尝试去探究其区别.

区别

大致整合区别如下:
1. interface的语义应该是高层的抽象, 他的所有特性都应该由实现类来体现, 常量违背了interface的定义.
2. interface提供的应该是提供服务的对象, 而不是提供数据
3. 常量将被直接编译到引用的文件中, 如果要修改就需要重新编译所有相关文件. (class和interface都一样适用)
4. 如果使用class + get方法提供常量的访问, 则可以实现动态编译, 只需要重新编译常量所在文件即可.

测试

初始值

初始值

所有常量值后拼接”.now”,并重新编译常量文件, 但不编译引用常量的文件

实验结果

code

public interface InterfaceA {    String CONSTANT = "interface.constant"; // to interface.constant.new}public class ClassA {    public static final String CONSTANT_A = "class.a";  // to class.a.new    private static final String CONSTANT_B = "class.b";  // to class.b.new    public static String getConstantB() {        return CONSTANT_B;    }}/** * 测试: (Main保持对常量的引用, 并不重新编译自己) * 1. 编译之后, 修改CONSTANT_A的值 * 2. 直接执行是否会变化? 如果重新编译ClassA呢? * 3. 同样的条件对CONSTANT_B, 结果是一样的吗? * 4. 同样的条件对interface呢? * * 结论: interface 和 class.a效果一样 * class.b完成了替换 * * @author guohang.ding on 17-2-6 */public class Main {    public static void main(String[] args) {        System.out.println("interface: " + InterfaceA.CONSTANT);        System.out.println("class.a: " + ClassA.CONSTANT_A);        System.out.println("class.b: " + ClassA.getConstantB());    }}

resources

某博客下评论, 不知来源

Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data.
As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class.

某链接

Java Interface 是常量存放的最佳地点吗?

0 0
原创粉丝点击