接口常量有什么用? [英] What is the use of interface constants?
问题描述
我正在学习Java,并且发现接口可以包含公共静态和最终的字段。到目前为止,我还没有看到这些例子。这些接口常量的一些用例有哪些,我可以在Java标准库中看到一些吗?
I am learning Java and just found that the Interface can have fields, which are public static and final. I haven't seen any examples of these so far. What are some of the use cases of these Interface Constants and can I see some in the Java Standard Library?
推荐答案
放置静态成员进入一个接口(并实现该接口)一个不好的做法,甚至有一个名称,常量接口反模式,请参阅 Effective Java ,Item 17:
Putting static members into an interface (and implementing that interface) is a bad practice and there is even a name for it, the Constant Interface Antipattern, see Effective Java, Item 17:
常量接口模式是接口使用不佳。一个类在内部使用一些常量是一个实现细节。实现常量接口会导致此实现细节泄漏到类的导出API中。类的用户实现一个常量接口并不重要。事实上,它甚至可能使他们感到困惑。更糟糕的是,它代表了一种承诺:如果在将来的版本中修改了类以便它不再需要使用常量,它仍然必须实现接口以确保二进制兼容性。如果非最终类实现了一个常量接口,那么它的所有子类的命名空间都会受到接口中常量的污染。
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
java平台库中有几个常量接口,例如 java.io.ObjectStreamConstants
。这些接口应该被视为异常,并且不应该模仿
。
There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants
. These interfaces should be regarded as anomalies and
should not be emulated.
为了避免常量接口的一些缺陷(因为你不能阻止人们实现它),应该首选一个带私有构造函数的适当类(例如借用维基百科):
To avoid some pitfalls of the constant interface (because you can't prevent people from implementing it), a proper class with a private constructor should be preferred (example borrowed from Wikipedia):
public final class Constants {
private Constants() {
// restrict instantiation
}
public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}
并且无需完全限定它们即可访问常量(即无需使用类名称作为前缀,使用静态导入(自Java 5起):
And to access the constants without having to fully qualify them (i.e. without having to prefix them with the class name), use a static import (since Java 5):
import static Constants.PLANCK_CONSTANT;
import static Constants.PI;
public class Calculations {
public double getReducedPlanckConstant() {
return PLANCK_CONSTANT / (2 * PI);
}
}
这篇关于接口常量有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!