接口常量有什么用? [英] What is the use of interface constants?

查看:37
本文介绍了接口常量有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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,第 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 中.类实现常量接口对类的用户没有任何影响.事实上,它甚至可能使他们感到困惑.更糟糕的是,它代表了一种承诺:如果在未来的版本中修改了类,使其不再需要使用常量,它仍然必须实现接口以确保二进制兼容性.如果一个非final类实现了一个常量接口,那么它的所有子类的命名空间都会被接口中的常量污染.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆