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,
}
}
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?