Java Nested Interfaces

Like nested classes, Java also allows us to define an interface within another interface or a class. Such an interface is called a nested interface. The following examples show the possibilities that may exist:

1) Interface within Interface

interface OuterInterface {    
    ...    
    interface NestedInterface {        
        ...    
    }
}

 

2) Interface within Class

class OuterClass {    
    ...    
    interface NestedInterface {        
        ...    
    }
}

 

Similarities with nested classes:

Like nested classes. the nested interfaces are also used to provide an easily readable and maintainable code. The nested interface can’t be accessed directly (i.e. similar to nested class). So, it must be referred by its outer interface or outer class. 

 

Features of a Java nested interface:
  • A nested interface defined within an interface is by default public.
  • A nested interface defined within a class can have any access specifier (public, protected, private or default).
  • A nested interface is by default static.

 

 

Example 1

Following is an example of a nested interface within an interface.

NestedInterface01.java

interface Outer {  //outer interface
void method1();

interface Inner { //nested interface
void method2();
}
}

public class NestedInterface01 implements Outer.Inner {
@Override
public void method2() {
System.out.println("interface within interface");
}

public static void main(String[] args) {
Outer.Inner obj = new NestedInterface01();
obj.method2();
}
}

Output:

interface within interface

 

 

Example 2

The coding example below shows how a nested interface is defined within a class.

NestedInterface02.java

class Out {  //outer class

interface In { //nested interface
void show();
}
}

public class NestedInterface02 implements Out.In {
@Override
public void show() {
System.out.println("interface within interface");
}

public static void main(String[] args) {
Out.Inr obj = new NestedInterface02();
obj.show();
}
}

Output:

interface within class