Interface中的内部类 [英] inner class within Interface

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

问题描述

可以在界面中创建内部类吗?
如果是,为什么我们这样做?
无论如何我们不打算创建任何接口对象?

is that possible to create a inner class within an interface? If yes, why do we create like that? Anyways we are not going to create any interface objects?

他们在任何开发过程中都有帮助吗?

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

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

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