【发布时间】:2012-10-30 10:25:11
【问题描述】:
可能重复:
Interfaces with static fields in java for sharing ‘constants’
我们有很多需要在课堂和我的问题中使用的常量 是否是创建具有公共属性的接口的最佳实践 或者别的什么...
public static final String NAME = "Name";
谢谢!
【问题讨论】:
标签: java
可能重复:
Interfaces with static fields in java for sharing ‘constants’
我们有很多需要在课堂和我的问题中使用的常量 是否是创建具有公共属性的接口的最佳实践 或者别的什么...
public static final String NAME = "Name";
谢谢!
【问题讨论】:
标签: java
您应该为此使用不可实例化的类,而不是接口。
public final class Constants{
private Constants(){}
public static final String NAME = "Name";
// more constants
}
根据 Joshua Bloch 在Effective Java 中的说法,接口应该只定义行为:
常量接口模式是接口使用不当。 类在内部使用一些常量是一个实现细节。 实现一个常量接口会导致这个实现细节 泄漏到类的导出 API 中。对它没有任何影响 一个类的用户认为该类实现了一个常量接口。在 事实上,它甚至可能使他们感到困惑。更糟糕的是,它代表了一种承诺:如果 在未来的版本中,该类被修改,使其不再需要 要使用常量,它仍然必须实现接口 确保二进制兼容性。如果一个非final类实现了一个常量 接口,它的所有子类的命名空间都会被污染 通过接口中的常量。
来源:Effective Java,第 19 条:仅使用接口来定义类型
【讨论】:
我的建议是为常量创建一个类。不是接口,如果接口没有方法,那么它就没有达到它的目的。
在接口中放置常量是早期流行的技术 Java 时代,但现在许多人认为它是一种令人反感的使用 接口,因为接口应该处理由 一个对象,而不是它的数据。同样,类使用的常量是 通常是实现细节,但将它们放在接口中 将它们提升为类的公共 API。
看看here。
【讨论】:
-首先一口气回答你的问题......是的,这是可能的,事实上,如果你使用
public int x=5; 或者
int x=5,
这将始终被解释为 public static final int x=5;
-但这是不是正确的方法。
-你最好使用Enum或Class with Private Constructor来处理这个问题。
例如:
具有静态字段的类:
public class Test{
public final String NAME = "Name";
private Test(){}
}
}
【讨论】:
"A class with static methods and static fields are equivalent to Sigleton Class", But this should Not be used, as the loading of which class and when by JVM is not a definite process. So Singleton is a safe bet.
您应该避免在接口中使用此类常量。您可以采用 Sean Patrick Floyd 提出的解决方案。或者使用枚举类型作为常量。
public enum Constants {
NAME("Name");
private final String constant;
private Constats(String constat) {
this.constant = constant;
}
public String constant(){
return this.constat;
}
}
当您的代码需要它们时,您应该使用枚举类型。然后你将在你的代码中有顺序。
【讨论】: