【问题标题】:How nested interface in a class behave like? [duplicate]类中的嵌套接口如何表现? [复制]
【发布时间】:2015-12-01 07:11:33
【问题描述】:

以下代码,

interface SuperInterface{
    void f();
    interface StaticNestedInterface{    
    }
}

class Sub implements SuperInterface{
    public void f(){

    }
}

public class Dummy {

    public static void main(String[] args) {
        Sub x  = new Sub();
    }

}

编译器不会要求class Sub 实现interface StaticNestedInterface

class Sub 是有效的 java 代码吗?

【问题讨论】:

  • 如果它编译,它是有效的。嵌套接口仍然只是另一个接口,它的名称只是由外部接口限定。

标签: java interface inner-classes


【解决方案1】:
interface StaticNestedInterface{    
  void a();
  void b();
}

interface SuperInterface extends StaticNestedInterface{
    void f();
}
class Sub implements SuperInterface{
    //now compiler require all methods(a, b and f)
}

【讨论】:

  • 在你的回答中,StaticNestedInterface 实际上不是嵌套接口,它是SuperInterface 的父级。
  • @overexchange,你想实现两个接口,所以你需要这样,或者在类的定义中实现两个接口
【解决方案2】:

是的,它是有效的 Java 代码。 你只是在SuperInterface 中声明StaticNestedInterface。使用嵌套接口的一种方法是

interface SuperInterface {
    void f();

    StaticNestedInterface sni();

    interface StaticNestedInterface {
        void a();
    }
}


class Sub implements SuperInterface{
    public void f(){

    }

    @Override
    public StaticNestedInterface sni() {
        return null;
    }
}

【讨论】:

  • StaticNestedInterface 就像声明嵌套的用户定义数据类型一样吗?
  • 是的,interface 在这种情况下类似于 class。当您声明StaticNestedInterface 时,任何人都可以使用它。您仍然需要在SuperInterface 中放置一个方法以供类实现。超级接口和嵌套接口的行为与两个独立接口没有任何不同。这是因为,与类不同,接口不能是私有的/受保护的。
  • 两个独立的接口,你的意思类似于包和分包的概念。
  • 包不影响interface 的使用。您可以将它们保存在项目中的任何位置。我的意思是在单独的 java 文件中的任何地方定义的两个独立接口。
【解决方案3】:

是的,它是一个有效的 java 代码。 Java 编译器会创建public static SuperInterface$StaticNestedInterface{}

要使用嵌套接口class Sub implements SuperInterface.StaticNestedInterface,编译器会要求子类实现StaticNestedInterface上声明的方法

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2015-11-20
    • 2012-09-02
    • 1970-01-01
    • 2013-10-26
    • 2014-12-01
    相关资源
    最近更新 更多