Nested class inside an interface

与世无争的帅哥 提交于 2019-12-19 07:54:09

问题


The java compiler allows me write a Class definition inside an Interface . Are there any specific uses of this ?

interface ClassInterface {

  void returnSomething();
  int x = 10;

  class SomeClass {
    private int y;

    private void classDoingSomething() {         
    }
  }
}

Please explain .


回答1:


You would use it to tightly bind a certain type to an interface. Read This page for further information and an example of defining a class inside an interface.




回答2:


The uses are the same that a class nested in another class: it allows scoping the class to the interface. You could imagine something like this:

public interface Switch {

    public enum Status {
        ON, OFF;
    }

    void doSwitch();
    Status getStatus();
}

It avoids defining a top-level class named SwitchStatus (because Status could be a too generic name).



来源:https://stackoverflow.com/questions/9098235/nested-class-inside-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!