Java常量放在Class还是Interface?

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 是常量存放的最佳地点吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值