【问题标题】:Nested class inside an interface接口内的嵌套类
【发布时间】:2012-02-24 06:36:46
【问题描述】:

Java 编译器允许我在 Interface 中编写 Class 定义。这个有什么具体用途吗?

interface ClassInterface {

  void returnSomething();
  int x = 10;

  class SomeClass {
    private int y;

    private void classDoingSomething() {         
    }
  }
}

请解释一下。

【问题讨论】:

标签: java interface nested-class


【解决方案1】:

用途与嵌套在另一个类中的类相同:它允许将类范围限定为接口。你可以想象这样的事情:

public interface Switch {

    public enum Status {
        ON, OFF;
    }

    void doSwitch();
    Status getStatus();
}

它避免定义一个名为SwitchStatus 的顶级类(因为Status 可能是一个过于通用的名称)。

【讨论】:

    【解决方案2】:

    您可以使用它将某种类型紧密绑定到接口。阅读This 页面了解更多信息以及在接口中定义类的示例。

    【讨论】:

    • 确实..这里我用它来嵌入一个接口的Null object实现,所以我不需要为它创建一个类文件。
    猜你喜欢
    • 2011-08-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多