views:

75

answers:

1

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?

+3  A: 

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

Webinator
Can you add some examples of usage? I've tested something similar some time ago and haven't understood what can I gain from using this construction.
Roman
@Roman: well I remember I've encountered this on some project (relatively clean project would I add but they weren't mine) but I don't know if it's really clean or not. I've added a tiny example that looks like what I've seen but once again: this wasn't my code and I'm not using that construct so I'm not the most qualified to come up with valid examples :) IIRC the class inside was always named, for example *StateChecker* and calls would always look like: *A.StateChecker.check( a )* or something like that.
Webinator