Interfaces with Constants Only(java中通用常量定义)
2006-03-13 11:05
489 查看
Interfaces with Constants Only
Before the static import became available, a trick for avoiding the need to write the class name for static constants was to create an interface whose only purpose is to hold constants.
For example, say that you need the constants ALPHA and OMEGA for several different programs. The first option is to create a utility class that holds the constants. e.g.:
1 public class MyConstants
2public class OtherClass
2 public interface MyConstantsImpl
2public class OtherClass implements MyConstantsImpl
2{
3 public OtherClass()
4 {
5 System.out.println("ALPHA ="+ALPHA );
6
7 System.out.println("OMEGA ="+OMEGA );
8 }
9}
whcih is far more readable.
This technique, however, violates the object-oriented design of the language. That is, you are not really implementing anything. You would not think of a class that implements MyConstantsImpl as a MyConstants object in the sense of taking on an identifiable behavior of an interface.
So constants-only interfaces are ill advised and considered bad programming style . Use a class instead and then statically import the class.
Before the static import became available, a trick for avoiding the need to write the class name for static constants was to create an interface whose only purpose is to hold constants.
For example, say that you need the constants ALPHA and OMEGA for several different programs. The first option is to create a utility class that holds the constants. e.g.:
1 public class MyConstants
2public class OtherClass
2 public interface MyConstantsImpl
2public class OtherClass implements MyConstantsImpl
2{
3 public OtherClass()
4 {
5 System.out.println("ALPHA ="+ALPHA );
6
7 System.out.println("OMEGA ="+OMEGA );
8 }
9}
whcih is far more readable.
This technique, however, violates the object-oriented design of the language. That is, you are not really implementing anything. You would not think of a class that implements MyConstantsImpl as a MyConstants object in the sense of taking on an identifiable behavior of an interface.
So constants-only interfaces are ill advised and considered bad programming style . Use a class instead and then statically import the class.
相关文章推荐
- java中的常量,是不是必须定义为static final的呢
- java中的常量定义
- Java中定义常量几种方式
- 通过类字面常量解释接口常量为什么只能定义为static final,类加载过程---Thinking in java
- Java常量定义需要注意事项及static作用(复习)
- java如何引入接口中定义的常量
- 设计: ListView 接口,and the missing read-only interfaces in java collection framework
- java中定义常量
- 提高Java代码质量:使用枚举定义常量(转)
- Java常量的定义
- Java常量的定义
- 浅谈Java接口中为什么只能定义常量
- java.lang.IllegalStateException: Hardware acceleration can only be used with a single UI thread.
- JAVA中常量的一种定义方法
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- 通过类字面常量解释接口常量为什么只能定义为static final,类加载过程---Thinking in java
- JAVA final关键字,常量的定义
- JAVA中的常量定义在class中还是interface中比较合理?
- Java中定义Map常量,List常量
- 如何在Java中定义常量(Constant)