This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Declaring an interface inside an inner class gives a compile time error stating, static declarations are not allowed inside Inner class. I know this rule but interface isnt static. I beleive its because of the public STATIC final CONSTANTS that's causing a hindrance but the error is generated even when an empty body is declared for the interface and if IMPLICIT condition is responsible for this behaviour then why doesnt the compiler complain when an interface is declared outside a class in a program as :
Here if i save the program as B.java or with anyother name since nothing is EXPLICITLY DECLARED as public no issues but then if it interface A is assigned a public modifier EXPLICITLY the compler complains that the file should be named as A.java.....but then interfaces are implicitly public then why does the compiler not raise error with the latter code ?
I think inner (nested) interfaces are implicitly static, the same as enums. The reason is that there is no instance of the outer class involved, like there must be for regular (non-static) inner classes. Then, since you can't have static declarations in a regular inner class except for final variables that resolve to compile-time constants, you can't have instance declarations inside regular inner classes.
All code in my posts, unless a source is explicitly mentioned, is my own.
Joined: Dec 16, 2008
I checked TJLS, 8.1.3, and I can confirm that inner interfaces are implicitly static.
Another point that I want to make is that interfaces are not implicitly public like you said. If you have an interface with no access modifier, the interface will have default (package) access. You can do a test by declaring an interface without explicit access modifiers in a file in a package, and then try to access that interface from a class or interface in a different package.
Also, inner interfaces can have any access level (public, protected, default, or private.)
Joined: Jan 01, 2009
Thanks Ruben, i understood why Inner classes dont allow interfaces. And about interfaces being implicitly public , i was wrong...I misread the statement in K&B that Interface METHODS are implicitly public and abstract..Thanks again Ruben...Thanks a lot..
Joined: Dec 16, 2008
Yeah, no problem Abhishek. It is easy to get misconceptions like that, because all the methods and variables in an interface are implicitly public, so that might lead you to believe that interfaces themselves will be implicitly public. But they are just like classes in that respect.