A nested interface is an interface declared within another interface or class. Nested interfaces are used to group related interfaces to make the code easier to organize and maintain. A nested interface must be accessed through its outer interface or class and cannot be accessed directly.
When creating a nested interface, the following rules should be remembered:
A nested interface can be created by declaring it inside another interface or inside a class and it must be accessed through its outer interface or class and cannot be accessed directly.
The syntax to create a nested interface inside an interface is as follows:
The syntax to create a nested interface inside ac class is as follows:
The following example demonstrates creating and using a nested interface which is declared inside an interface:
Output:
hello nested interface
As you can see in the above example, we are accessing the Message interface by its outer interface Showable because it cannot be accessed directly. It is just like the almirah inside the room; we cannot access the almirah directly because we must enter the room first. In the collection framework, the sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map, i.e., accessed by Map.Entry.
The following example demonstrates creating and using a nested interface which is declared inside a class:
Let's see how we can define an interface inside the class and how we can access it.
Output:
hello nested interface
A class can be defined inside an interface, including a nested interface. When a class is defined inside an interface, the Java compiler automatically treats it as a static nested class. This allows the class to be accessed using the interface name without creating an instance of the interface.
The following example demonstrates creating a class inside an interface:
Output:
Class inside interface
We request you to subscribe our newsletter for upcoming updates.