Nested Interfaces in Java

Interfaces can be nested i.e one interface can be defined inside another interface. It can be defined inside another class as well.

  • Nested interfaces are implicitly static. So they can be used without object instantiation.
  • Interfaces nested inside another interface are implicitly public while interfaces nested inside another class can have any access modifier(public, protected, default, private).

When a nested interface is used outside of its enclosing class / interface, it must be qualified with the name of the class or interface of which it is a member.


1. An Interface can be nested inside a class

Let’s see an example to understand how an interface can be nested inside a class.

Output :

 


2. An Interface can be nested inside another Interface

Let’s see an example to understand how an interface can be nested inside another interface.

Output :

 


3. Advantages of Nested Interfaces.

  • It improves Encapsulation.
  • It improves code readability by grouping related interfaces at one place.
  • It also helps to avoid namespace collision in case of commonly used names.