java - 类内接口(interface)

标签 java class interface

在类内部、嵌套类内部和类外部使用接口(interface)有什么区别。

当我阅读有关类(class)的内容时 DataStructure.java Questions and Exercises: Nested Classes在 Oracle(此处粘贴示例片段):

public class DataStructure {
//some code
    interface DataStructureIterator extends java.util.Iterator<Integer> { } 

    // Inner class implements the DataStructureIterator interface,
    // which extends the Iterator<Integer> interface

    private class EvenIterator implements DataStructureIterator {
//rest code
  1. 正如代码所示,界面中没有任何主体。我不能用 java.util.Iterator<Integer> 扩展 EvenIterator 类吗?而不是创建这个接口(interface)并实现它?

  2. 在类外/类内声明干扰是否有任何其他区别(除了代码可读性之外)?

  3. 当外部类被接口(interface)扩展时会发生什么。它会对嵌套类产生任何影响吗?

只是想确定这些东西,以便知道如何正确使用它们,感谢您的宝贵时间。

最佳答案

  1. So as the code about shows there is no any body in interface. Couldn't I just extends EvenIterator class with java.util.Iterator instead of creating this interface and implements it?

是的,你可以。但是这样它可能更具可读性和可扩展性。即使现在没有成员,以后也可能会添加。

  1. Is there any other difference (aside from code readability) between declaring interference outside/inside class?

嵌套接口(interface)是隐式静态的,因此唯一的影响是嵌套接口(interface)是封闭类命名空间的一部分。

因为类的成员可能被声明为protectedprivate,这也适用于嵌套接口(interface)。但是,使用 private 接口(interface)几乎没有意义,因为它们只能在同一个类中实现,那么为什么一开始就麻烦接口(interface)呢?但是,protected 接口(interface)可能会有用。例如,您可能有一个抽象工厂方法,子类使用该方法向父类提供实例。这是一个人为的例子:

public abstract class Enclosing {

    protected interface JobHandler {
        void handle(Job job) throws JobException;
    }

    protected abstract JobHandler createJobHandler();

    // public methods omitted

    private void doTheJob(Job job) {
        createJobHandler().handle(job);
    }
}

如果接口(interface)被声明为包私有(private)的,它也可能只是在包级别。您可能希望将它塞进一个类中的唯一原因是因为它与类本身紧密耦合。也许它是某种辅助接口(interface),严格用于对该特定类进行单元测试。

如果接口(interface)是public,那么嵌套它通常不是一个好主意。因为这样做会增加接口(interface)和封闭类之间的耦合。接口(interface)是减少耦合的最佳方式之一!那么为什么要浪费他们的潜力呢?

假设您有一个 mylib-buttons 库,其中有一个 Button 类。有一天,拥有一个 Button.ClickListener 似乎是个好主意。然后你想在另一个类中重用这个接口(interface),甚至可能在另一个库中。但是如果不引入对包含 Button 类的库的(可能是不必要的)依赖性,您就无法做到这一点。另一方面,如果它是一个顶级界面,那么你只需将界面提取到另一个库中,比如 mylib-core,将凌乱的按钮单独留在 mylib-buttons.

interfaces 中的嵌套接口(interface)有点不同。它们可以是同一设计的一部分,并且可以一起使用。 @cricket_007 在其中一条评论中给出了一个很好的例子:Map.Entry

  1. What will happen when the outer class gonna be extended by a interface. Will it impact in any way on nested class?

这不是很清楚。如何通过接口(interface)扩展类?然而,无论您在这里的意思是什么,如果您考虑到上述事实,您可能会自己回答:嵌套接口(interface)只是类的命名空间范围的一部分,仅此而已。没有任何其他影响。

关于java - 类内接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530066/

相关文章:

java - 尝试通过代理创建 HttpsURLConnection 时出现错误

c++ - 窗口包装类 C++ (G++)

未强制执行 C++ 虚函数

java - 再次重写与重载

typescript - 将枚举导入到接口(interface)会破坏接口(interface)

java - 在 Java 中实例化接口(interface)

java - 教程第 6 部分中出现错误 : JSON Parsing and Android ListView Design

java - JTable-在应用默认 Nimbus 样式时覆盖prepareRenderer?

java - 在 Java 中遵循 if-else 阶梯的更好选择是什么?

java - 在 Java 中获取 super 接口(interface)