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

查看:35
本文介绍了为什么要在 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关键字是多余的(嵌套接口自动为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 是包私有的,字节码或反射也可以访问 Foo.Bar!)

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天全站免登陆