接口内的内部类 [英] Inner class within Interface

查看:31
本文介绍了接口内的内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在接口内创建内部类?
如果可能的话,我们为什么要创建一个内部类,因为我们不打算创建任何接口对象?

Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since we are not going to create any interface objects?

这些内部类对任何开发过程有帮助吗?

Do these inner classes help in any development process?

推荐答案

是的,您可以在 Java 接口中创建嵌套类或内部类(请注意,与流行的看法相反,没有诸如静态内部类"之类的东西:这根本没有意义,当嵌套类是静态的时,没有内部"和外部"类,因此它不能是静态内部").

Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner").

无论如何,以下编译正常:

Anyway, the following compiles fine:

public interface A {
    class B {
    }
}

我已经看到它曾经在接口定义中直接放置某种合同检查器"(嗯,在嵌套在接口中的类中,可以有静态方法,与接口本身相反,它不能).如果我没记错的话,看起来像这样.

I've seen it used to put some kind of "contract checker" directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can't). Looking like this if I recall correctly.

public interface A {
    static class B {
        public static boolean verifyState( A a ) {
            return (true if object implementing class A looks to be in a valid state)
        }
    }
}

请注意,我不是在评论这种东西的用处,我只是在回答你的问题:它可以做到,这是我见过的一种用途.

Note that I'm not commenting on the usefulness of such a thing, I'm simply answering your question: it can be done and this is one kind of use I've seen made of it.

现在我不会评论这样一个结构的用处,从我所看到的:我已经看到了它,但它不是一个非常常见的结构.

Now I won't comment on the usefulness of such a construct and from I've seen: I've seen it, but it's not a very common construct.

这里有 200KLOC 代码库,这种情况恰好是零时间发生的(但是我们还有很多其他事情,我们认为这些错误的做法也恰好是零时间发生的,而其他人会认为这是完全正常的......).

200KLOC codebase here where this happens exactly zero time (but then we've got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so...).

这篇关于接口内的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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