实现声明嵌套接口的父接口时会发生什么

What happens when implementing Parent interface that declares a Nested Interface

我搜索了 Google 但没有找到可以消除我疑惑的具体示例。假设我有一个带有嵌套接口的父接口。

例如

public interface A {
    .. methods

    interface B {
        .. methods
    }
}

如果 class 实现了接口 A,会发生什么,class 是否也在内部实现了嵌套接口 B,这意味着我是否也应该覆盖接口 B 的方法?

没有。 必须实现内部接口。

语法为

Class C implements A, A.B{
// add methods here
}

如果只实现 A,只声明 A 的方法而不声明 B 的接口方法就可以了。

由于接口没有方法的实现,因此在实现外部接口时不需要实现嵌套接口。
内部接口更像是位于外部接口命名空间中的接口。

总结一下:接口之间没有任何关系,您可以像处理两个独立的接口一样处理它们。唯一的关系是您只能通过调用 A.instanceofB.method();.

来使用接口 B

接口:

interface OuterInterface {
    String getHello();

    interface InnerInterface {
        String getWorld();
    }
}

示例:

static class OuterInterfaceImpl implements OuterInterface {
    public String getHello() { return "Hello";}
}

public static void main(String args[]) {
    new OuterInterfaceImpl().getHello(); // no problem here
}

示例 2:

static class InnterInterfaceImpl implements OuterInterface.InnerInterface {
    public String getWorld() { return "World";}
}

public static void main(String args[]) {
    new InnerInterfaceImpl().getWorld(); // no problem here
}

示例 3:

static class OuterInterfaceImpl implements OuterInterface {
    public String getHello() { return "Hello"; }

    static class InnerInterfaceImpl implements InnerInterface {
        public String getWorld() { return "World!"; }
    }
}

public static void main(String[] args) {
    OuterInterface oi = new OuterInterfaceImpl();
    OuterInterface.InnerInterface ii = new OuterInterfaceImpl.InnerInterfaceImpl();
    System.out.println(oi.getHello() + " " + ii.getWorld());
}

在基本情况下,在接口中,除方法声明之外的任何内容都是 public 静态的。任何静态的东西都不能被继承。因此,嵌套接口必须单独实现。