A Guide to Inner Interfaces in Java – Java中的内部接口指南

最后修改: 2017年 12月 15日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this short tutorial, we’ll be looking at inner interfaces in Java. They are mainly used for:

在这个简短的教程中,我们将看看Java的内部接口。它们主要用于。

  • solving the namespacing issue when the interface has a common name
  • increasing encapsulation
  • increasing readability by grouping related interfaces in one place

A well-known example is the Entry interface which is declared inside the Map interface. Defined this way, the interface isn’t in global scope, and it’s referenced as Map.Entry differentiating it from other Entry interfaces and making its relation to Map obvious.

一个著名的例子是Entry接口,它被声明在Map接口内。以这种方式定义,该接口不在全局范围内,它被引用为Map.Entry,以区别于其他Entry接口,并使其与Map的关系变得明显。

2. Inner Interfaces

2.内部接口

By definition, declaration of an inner interface occurs in the body of another interface or class.

根据定义,内部接口的声明发生在另一个接口或类的主体中。

They are implicitly public and static as well as their fields when declared in another interface ( similar to field declarations in top-level interfaces), and they can be implemented anywhere:

当在另一个接口中声明时,它们和它们的字段一样是隐含的公共的和静态的(类似于顶级接口中的字段声明),它们可以在任何地方实现。

public interface Customer {
    // ...
    interface List {
        // ...
    }
}

Inner interfaces declared within another class are also static, but they can have access specifiers which can constrain where they can be implemented:

在另一个类中声明的内部接口也是静态的,但是它们可以有访问指定符,从而限制它们可以在哪里实现。

public class Customer {
    public interface List {
        void add(Customer customer);
        String getCustomerNames();
    }
    // ...
}

In the example above, we have a List interface which will serve as declaring some operations on list of Customers such as adding new ones, getting a String representation and so on.

在上面的例子中,我们有一个List接口,它将用于声明对Customers列表的一些操作,例如添加新的客户、获得String表示等等。

List is a prevalent name, and to work with other libraries defining this interface, we need to separate our declaration, i.e., namespace it.

List 是一个普遍的名字,为了和其他定义这个接口的库一起工作,我们需要把我们的声明分开,也就是namespace it。

This is where we make use of an inner interface if we don’t want to go with a new name like CustomerList.

如果我们不想使用像CustomerList.这样的新名字,我们就在这里使用一个内部接口。

We also kept two related interfaces together which improves encapsulation.

我们还把两个相关的接口放在一起,这提高了封装性。

Finally, we can continue with an implementation of it:

最后,我们可以继续对其进行实施。

public class CommaSeparatedCustomers implements Customer.List {
    // ...
}

3. Conclusion

3.总结

We had a quick look at inner interfaces in Java.

我们快速浏览了一下Java的内部接口。

As always, code samples can be found over on GitHub.

一如既往,代码样本可以在GitHub上找到over