我刚刚在我们的代码库中发现了一个静态嵌套接口。

class Foo {
    public static interface Bar {
        /* snip */
    }
    /* snip */
}

我以前从未见过这个。原来的开发人员已经找不到了。因此我不得不问SO:

静态接口背后的语义是什么?如果我移除这些静电,会发生什么变化?为什么会有人这么做?


当前回答

1998年,Philip Wadler提出了静态接口和非静态接口之间的区别。

在我看来,唯一的区别是 接口非静态是指它现在可以包含非静态的内部 类;所以这个改变不会使任何现有的Java无效 项目。

例如,他提出了“表达问题”的解决方案,即“你的语言能表达多少”的表达与“你试图用你的语言表达的术语”的表达之间的不匹配。

静态和非静态嵌套接口之间的区别可以在他的示例代码中看到:

// This code does NOT compile
class LangF<This extends LangF<This>> {
    interface Visitor<R> {
        public R forNum(int n);
    }

    interface Exp {
        // since Exp is non-static, it can refer to the type bound to This
        public <R> R visit(This.Visitor<R> v);
    }
}

他的建议从未出现在Java 1.5.0中。因此,所有其他答案都是正确的:静态和非静态嵌套接口没有区别。

其他回答

如果你将类Foo改为接口Foo,上面例子中的“public”关键字也将是多余的,因为

在另一个接口中定义的接口将隐式公开 静态的。

静态意味着包(项目)的任何类都可以在不使用指针的情况下访问它。根据情况,这可能是有用的,也可能是阻碍的。

“静态”方法的最佳示例是Math类。数学中的所有方法都是静态的。这意味着你不需要走出去,创建一个新的实例,声明变量并将它们存储在更多的变量中,你只需要输入你的数据并得到一个结果。

静态并不总是那么有用。例如,如果您正在进行案例比较,您可能希望以几种不同的方式存储数据。您不能创建三个具有相同签名的静态方法。你需要3个不同的实例,非静态的,然后你可以比较,因为如果它是静态的,数据不会随着输入而改变。

静态方法适用于一次性返回和快速计算或容易获得的数据。

Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)

在Java中,静态接口/类允许接口/类像顶级类一样使用,也就是说,它可以由其他类声明。所以,你可以:

class Bob
{
  void FuncA ()
  {
    Foo.Bar foobar;
  }
}

如果没有静态,上述代码将无法编译。这样做的好处是,您不需要一个新的源文件来声明接口。它还可视化地将接口Bar与类Foo关联起来,因为你必须编写Foo。Bar并暗示Foo类对Foo.Bar的实例做一些事情。

Java中类类型的描述。

The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).