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

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

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

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


当前回答

要非常直接地回答你的问题,请查看Map.Entry。

地图。条目

这也可能是有用的

静态嵌套Inerfaces博客条目

其他回答

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)

Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.

class ConcreteA implements A {
 :
}

class ConcreteB implements B {
 :
}

class ConcreteC implements C {
 :
}

class Zoo implements A, C {
 :
}

class DoSomethingAlready {
  interface AC extends A, C { }

  private final AC ac;

  DoSomethingAlready(AC ac) {
    this.ac = ac;
  }
}

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

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

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

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

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).

内部接口必须是静态的,才能被访问。该接口与类的实例无关,而是与类本身相关,因此可以通过Foo访问它。酒吧,像这样:

public class Baz implements Foo.Bar {
   ...
}

在大多数情况下,这与静态内部类没有什么不同。