Java常量放在Class还是Interface?
2017-02-06 18:45
477 查看
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中常量定义在interface中好还是定义在class中好" 的一些思考
- JAVA中的常量定义在class中还是interface中比较合理?
- java中常量定义在interface中好还是定义在class中
- JAVA中的常量定义在class中还是interface中比较合理?
- Java中定义常量方法及建议(Class/Interface)
- 常量放在java接口里还是java类里的问题
- 静态常量使用class还是interface?
- Java中常量定义在interface和class的区别(转)
- Hibernate3.5却报异常 java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface
- "Interface1.java": 'class' or 'interface' expected at line 19, column 17
- java web开发,bean数据放在request、response还是servletcontext中?
- java中看class,interface之间的extends,implements的关系,,用F4,open type hierarchy
- difference between Abstract class and interface in java
- java interface vs abstract class
- Java中JAXB相关的重要Class和Interface
- class,abstract class,interface之间的继承与实现关系(java,c#)
- Java的类(class)、包(package)和接口(interface)
- StaticTest.java:1 错误:需要class,interface或enum
- Java Abstract class and Interface