Nested interfaces (inner interfaces) are interfaces declared within other classes or interfaces. They first appeared in the language to structure large classes and hide implementation details. This encapsulation allows for logical grouping of contracts, significantly improving code readability and maintainability.
From the first versions of Java, it became possible to declare static and non-static nested interfaces within classes and other interfaces. This practice spread in large libraries (for example, in Java collections).
Misunderstanding the visibility and scope of nested interfaces often leads to API design errors and complicates application architecture. They cannot be used as instance members; they are always static by nature.
Nested interfaces are used to provide a more modular structure and highlight specific contracts that only relate to the enclosing class. For example, the Entry interface inside Map:
public interface Map<K, V> { interface Entry<K, V> { K getKey(); V getValue(); } Set<Entry<K, V>> entrySet(); }
Key features:
Question 1: Can you create an instance of a nested interface without having an instance of the outer class?
Yes, an instance of a nested interface can be implemented separately, without creating an outer object, as the interface is nested statically.
Question 2: What is the scope of a nested interface within a class?
The scope is regulated by modifiers (public, protected, private, package-private). However, they are often made public if external access is needed.
Question 3: Can a nested interface contain nested interfaces?
Yes, any level of nesting of interfaces is allowed, although in practice this is rare due to decreased readability.
In one large project, 10+ nested interfaces were defined inside the Service class. The number of connections grew, navigation and understanding of the code worsened.
Pros:
Cons:
In the DataProcessor class, a nested interface Validator was defined, which only implemented within DataProcessor and nowhere else.
Pros:
Cons: