为什么语言设计者允许接口包含字段? [英] Why language designers allow interface to contain fields?

查看:110
本文介绍了为什么语言设计者允许接口包含字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Effective Java中的第19项,必须使用一个接口来表示一个类型。在这种情况下,接口将包含构成公共合同一部分的方法,这些方法由类(实现接口)向客户端公开

As per Item 19 in Effective Java, one must use an interface to only represent a type. In this case the interface would contain the methods that form part of the public contract that is exposed by a class (implementing the interface) to the clients

如果是这样,为什么呢?接口首先支持字段?由于字段是隐式公共的,静态的,最终的(以及因此常量),为什么语言设计者支持它们呢?如果它们不受支持,那么开发人员总是会使用utils类(使用私有构造函数)来定义这些常量。可以自动避免使用常量仅使用接口的反模式

If so, why do interfaces support fields in the first place? Since the fields are implicitly public, static, final, (and hence constants), why did the language designers support having them? If they were unsupported then developers would invariably use utils class (with private constructor) to define these constants. The anti pattern of using constants only interfaces could have been automatically avoided

我正在研究在界面中理解支持常量的原因。作为与客户的合同的一部分,它们是否必不可少?

I am looking at understanding the reasons for supporting constants in the interface. Are they essential as part of the contract with the client?

谢谢

推荐答案

一个原因可能是对接口合同至关重要的常量。例如,请考虑以下界面:

One reason might be constants which are essential to the interface's contract. For instance, consider the following interface:

/**
* Generates a probability distribution on a
* specified interval.
*/
public interface DistributionGenerator{
    /*
    * Gets a probability distribution on the specified
    * interval. The exact distribution is unique to the 
    * implementor of this interface. The distribution will
    * be represented as an array of doubles. The first number
    * in the returned array will be the probability at start
    * The last number will be the probability at end. All numbers
    * in between will be probabilities at evenly spaced 
    * intervals between start and end, with the spacing between values
    * given by the constant INTERVAL
    */
    public double[] getDistribution(double start,double end);

    public static final double INTERVAL = 0.000001;
}

但是,正如您所观察到的,大多数情况下您会在界面中看到常量为了自己的利益简单地公开常量,这是通常被认为是坏的练习

However, as you observed, most of the time you see constants in interfaces it is done to simply expose the constants for their own sake, and this is generally considered bad practice.

这篇关于为什么语言设计者允许接口包含字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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