Why would a static nested interface be used in Java?

The static keyword in the above example is redundant (a nested interface is automatically “static”) and can be removed with no effect on semantics; I would recommend it be removed. The same goes for “public” on interface methods and “public final” on interface fields – the modifiers are redundant and just add clutter to the source code.

Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code – bytecode or reflection can access Foo.Bar even if Foo is package-private!)

It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:

public class Foo {
    public interface Bar {
        void callback();
    }
    public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
    public void callback() {...}
});

Leave a Comment