Can a class have an interface?

Total Post:397

 1209  View(s)
Rate this:
Yes, it is known as nested interface.
  1. Post:397

    Re: Can a class have an interface?

    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...).
    A valid use, IMHO, is defining objects that are received or returned by the enclosing interface methods. Tipically data holding structures. In that way, if the object is only used for that interface, you have things in a more cohesive way.

    By example:

    interface UserChecker {
       Ticket validateUser(Credentials credentials);
       class Credentials {
          // user and password
       class Ticket {
          // some obscure implementation
    But anyway... it's only a matter of taste.