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 是常量存放的最佳地点吗?
- Java常量放在Class还是Interface?
- JAVA中的常量定义在class中还是interface中比较合理?
- 常量放在java接口里还是java类里的问题
- 基本数据类型数据是放在栈还是常量池?
- Java中的常量该放在哪?
- 关于 "java中常量定义在interface中好还是定义在class中好" 的一些思考
- Java Interface & Abstract Class
- Java Interface & Abstract Class
- Java Interface & Abstract Class
- JAVA---interface和class
- 【转载】该用 Abstract Class 还是 Interface?
- Java Interface and Class Hierarchy
- effective java -Class and Interface
- java interface vs abstract class
- java interface and abstract class
- java:错误,需要class,interface
- Java abstract class vs interface
- Java-Abstract Class and Interface
- Thinkphp 3.1.* session 指向redis
- leetcode_middle_23_452. Minimum Number of Arrows to Burst Balloons
- poi文件上传
- 哈希算法hash
- 全排列问题 递归算法
- Java常量放在Class还是Interface?
- Android 4.x touchmove事件兼容问题
- 修改searchview搜索框光标
- 2016届蓝桥杯省赛B组第三题
- 假期训练——Mahjong HDU - 4431 模拟
- GitHub--平时Coding
- JavaSE_11th_JDK_API文档
- php通过ssh2扩展控制linux,模拟阿里云web控制台
- matlab与C对照以及matlab之_极限_微分_积分_定积分