Why should we declare an interface inside a class?

When you want to gather some fields in an object in order to emphasize a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).

If you want to emphasize the fact that this cooperative class makes strictly no sense (has no use) outside the original object use, you could make it nested/inner.

Thus, when dealing with some hierarchy, you can describe a "nested" interface, which will be implemented by the wrapping class's subclasses.

In the JDK, the most significant example would be Map.Entry inner interface, defined within Map interface and implemented by various ways by HashMap, LinkedHashMap etc...

And of course, Map.Entry needed to be declared as public in order to be accessible while iterating the map wherever the code is.


If the interface definition is small and the interface will only be used by clients of the class it's defined in, it's a good way to organize the code. Otherwise, the interface should be defined in its own file.


This is inner interface. Java programming language allows defining inner classes and interfaces. This is typically useful if you want to limit visibility of this class or interface by scope of current outer class.

Some people use this mechanism for creating a kind of namespace. IMHO this is abuse of the language feature (in most cases).