为什么接口中的所有字段都是隐式静态和最终的? [英] Why are all fields in an interface implicitly static and final?

查看:26
本文介绍了为什么接口中的所有字段都是隐式静态和最终的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想了解为什么接口中定义的所有字段都是隐式staticfinal.保持字段 static 的想法对我来说很有意义,因为您不能拥有接口的对象,但为什么它们是 final(隐式)?

I am just trying to understand why all fields defined in an Interface are implicitly static and final. The idea of keeping fields static makes sense to me as you can't have objects of an interface but why they are final (implicitly)?

有人知道为什么 Java 设计者要在接口 staticfinal 中创建字段吗?

Any one knows why Java designers went with making the fields in an interface static and final?

推荐答案

接口旨在指定交互契约,而不是实现细节.开发人员应该能够仅通过查看接口来使用实现,而不必查看实现它的类的内部.

An interface is intended to specify an interaction contract, not implementation details. A developer should be able to use an implementation just by looking at the interface, and not have to look inside the class which implements it.

接口不允许您创建它的实例,因为您不能指定构造函数.所以它不能有实例状态,尽管接口字段可以定义常量,这些常量是隐式静态和最终的.

An interface does not allow you to create an instance of it, because you cannot specify constructors. So it cannot have instance state, although interface fields can define constants, which are implicitly static and final.

您不能在接口中指定方法主体或初始化程序块,尽管从 Java 8 开始您可以使用主体指定默认方法.此功能旨在允许将新方法添加到现有接口,而无需更新所有实现.但是如果不先创建一个实现接口的实例,你仍然无法执行这样的方法.

You cannot specify method bodies or initializer blocks in an interface, although since Java 8 you can specify default methods with bodies. This feature is intended to allow new methods to be added to existing interfaces without having to update all the implementations. But you still cannot execute such a method, without first creating an instance implementing the interface.

旁白:请注意,您可以使用匿名内部类来实现接口:

Aside: Note that you can implement an interface with an anonymous inner class:

interface Foo {
    String bar();
}

class FooBar {
    Foo anonymous = new Foo() {
         public String bar() {
             return "The Laundromat Café";
    };
}

您必须为匿名内部类提供接口的完整实现才能进行编译.

You have to provide the full implementation of the interface for the anonymous inner class to compile.

new Foo() 正在使用其默认构造函数初始化匿名内部类.

new Foo() is initializing the anonymous inner class with its default constructor.

这篇关于为什么接口中的所有字段都是隐式静态和最终的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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