Java: Nested Interface

An interface declared within another interface or class is called a nested interface.

The nested interfaces in java are used to group related interfaces so that easily maintain. The nested interface can’t be accessed directly. For accessing must be referred to by the outer interface or class.

For example, the Nested interface is just like almirah inside the room, for accessing almirah, first need to enter the room.

In the java collection framework,  Entry is the subinterface of Map i.e. accessed by Map. Entry.

Points to remember for nested interfaces

  • Nested interfaces are declared static implicitly.
  • Nested interface can have any access modifier while inside the class but if use inside interface then it must be public.

Syntax of Nested Interface inside Class

class class_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}

Syntax of Nested Interface inside Interface

interface interface_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}  

Example of Nested Interface: Interface within Interface

interface Readable{
  void show();
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Interface

we are accessing the Message interface by its outer interface Readable because it cannot be accessed directly.

class NestedInterfaceExample1 implements Readable.Message{

 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
  //upcasting here
  Readable.Message message=new NestedInterfaceExample1();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Note: For the above example when you compile Readable class, compiler internally creates the public and static interface as given below:

public static interface Showable$Message
{
  public abstract void messageDetail();
}

As you can see in the above example, The java compiler internally creates the public and static interface.

Example of Nested Interface: Interface within Class

In the below example you will see, interface implementation inside the class and how can we access it.

class ClassA{
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Class

class NestedInterfaceExample2 implements ClassA.Message{
 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
 //upcasting here
  ClassA.Message message=new NestedInterfaceExample2();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Can we define a class inside the interface?

Yes, If we implement a class inside the interface, the java compiler automatically creates a static nested class. In this example you will see how can we define a class within the interface:

interface M{
class A{}
}