FAQ

Java

JSP

Servlet


Advertisement



Why an interface can't be defined in an inner class

According to JLS: 8.1.3 Inner Classes and Enclosing Instances, inner classes may not declare static initializers or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields.

According to 8.5.2 Static Member Type Declarations, "Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier". They are always top-level, not inner.

Therefore, an interface can't be defined in an inner class. The member interface can only be defined in inside a top-level class or interface. For example,

interface OuterInterface { // Top-level interface

interface NestedInterface {// top-level nested interface
}

}

class OuterClass {

/*Nested top-level classes are always defined with a static keyword*/
static class NestedClass {
interface NestedInterface { } //OK
}

/*Inner class */
class InnerClass {

/* This will cause an error. Because, you can not define a static modifier
inside an inner class. InnerClass is an inner class and NestedInterface
is implicitly static. An compile time error will occurs.
*/

interface NestedInterface { //compile time error,
}
}
}


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |