为什么在Java中使用静态嵌套接口? [英] Why would a static nested interface be used in Java?

查看:96
本文介绍了为什么在Java中使用静态嵌套接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚在代码库中找到了一个静态嵌套接口。

I have just found a static nested interface in our code-base.

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

我以前从未见过这个。最初的开发者是遥不可及的。因此我不得不问:

I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:

静态接口背后的语义是什么?如果我删除 static ,会有什么变化?为什么有人会这样做?

What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?

推荐答案

上例中的static关键字是冗余的(嵌套接口自动为静态)并且可以删除而不会影响语义;我建议将其删除。接口方法中的public和接口字段上的public final也是如此 - 修饰符是冗余的,只是为源代码添加了混乱。

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.

无论哪种方式,开发人员只是声明一个名为Foo.Bar的接口。除了无法访问Foo的代码也无法访问Foo.Bar之外,没有与封闭类的进一步关联。 (从源代码 - 字节码或反射可以访问Foo.Bar,即使Foo是包私有的!)

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() {...}
});

这篇关于为什么在Java中使用静态嵌套接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆