An interface which is declared inside another interface or class is called nested interface. They are also known as inner interface. Since nested interface cannot be accessed directly, the main purpose of using them is to resolve the namespace by grouping related interfaces (or related interface and class) together. This way, we can only call the nested interface by using outer class or outer interface name followed by dot( . ), followed by the interface name.
Example: Entry interface inside Map interface is nested. Thus we access it by calling Map.Entry.
Note:
- Nested interfaces are static by default. You don’t have to mark them static explicitly as it would be redundant.
- Nested interfaces declared inside class can take any access modifier, however nested interface declared inside interface is public implicitly.
Example 1: Nested interface declared inside another interface
interface MyInterfaceA{ void display(); interface MyInterfaceB{ void myMethod(); } } class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB{ public void myMethod(){ System.out.println("Nested interface method"); } public static void main(String args[]){ MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1(); obj.myMethod(); } }
Output:
Nested interface method
Example 2: Nested interface declared inside a class
class MyClass{ interface MyInterfaceB{ void myMethod(); } } class NestedInterfaceDemo2 implements MyClass.MyInterfaceB{ public void myMethod(){ System.out.println("Nested interface method"); } public static void main(String args[]){ MyClass.MyInterfaceB obj= new NestedInterfaceDemo2(); obj.myMethod(); } }
Output:
Nested interface method
Ram Kumar Shrestha says
In Example 1 of Nested Interface you are creating an object by referencing the inner interface via interface
//MyInterfaceA.MyInterfaceB = new NestedInterfaceDemo1();
What is the difference or advantage of doing so instead of referencing by
class name //InterfaceDemo obj = new Nested InterfaceDemo1();