java - 今天接口(interface)中的字段有好的用例吗?

标签 java interface ambiguity

Java 允许接口(interface)中的字段。这在 Java 5 之前有一些用处。他们今天有什么好的用例吗?

有人可以给我一些很好的用例,在这些用例中可以使用接口(interface)中的字段而不是许多其他方法来满足相同的设计要求吗?

事实上,接口(interface)在某些情况下允许歧义和混淆。举个例子。以下代码:

请注意,我知道歧义问题之前已经讨论过并回答过,但这不是我的问题。我的问题在上面用粗体标出。这只是接口(interface)中字段的一个潜在副作用的说明。

public class Sample implements Foo,Bar{

    public void print() {
        System.out.println("Hello"+name);//field name is ambiguous
    }

    public static void main(String[] args) {
        Sample mySample = new Sample();
        mySample.print();
    }

}

public interface Foo {
    String name = "foo";
}

public interface Bar{
    String name = "bar";
}

最佳答案

接口(interface)是用来定义契约的,常量是实现细节。如果多个实现共享一个常量是合理的,您可以在将用作层次结构的基类的抽象类中定义它。如果只有一个类真正绑定(bind)到常量,您应该在那里声明它。

如果你只想将一定数量的常量组合在一起,你可以在final类中定义它们:

final class Constants { //non extendable
    public static final double PI = 3.14d;
    public static final double E = 2.13d; //Can't remember the real value!

    private Constants() {} //non instantiable
}

当它们是枚举(例如颜色)时,您也可以在枚举中声明它们。

Effective Java Item #19“Use interfaces only to define types”中有更多关于它的内容,它的结尾是:

In summary, interfaces should be used only to define types. They should not be used to export constants.

最重要的是,总有一种比在接口(interface)中定义常量更好的方法。

关于java - 今天接口(interface)中的字段有好的用例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201717/

相关文章:

java - Guava EventBus 延迟嵌套事件的处理程序执行

python - 向客户端呈现 REST Web 服务界面

c++ - 关于多重继承和歧义

Java do while, while

c++ - 重载调用不明确

java - Spring REST 安全 : Enable Basic Authentication only on a specific endpoint

java - 有没有办法更新 Reactor 3 中的上下文?

c# - 具有接口(interface)类型的接口(interface)无法强制转换

java - Java多线程问题: How to clear last element in a list when update method is no longer called?

c++ - 在主应用程序中声明的 dll 中实现接口(interface) - C++