您的位置:首页 > 编程语言 > Java开发

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: