«Back to Home

Core Java

Topics

Nested Interface In Java

Nested Interface

When an interface is declared within another interface or a class, it is called as a nested interface.
 
The nested interface is used to group the related interfaces with the help of which, it becomes easy to maintain the code. The nested interface should be referred through the outer interface or class. It can't be accessed directly.
 
Nested interface should be public, if it is declared inside the interface but it can have any access modifier (public, private or protected), if declared within the class.
 
Nested interfaces are static by default.
 
Syntax

This is declared within the interface.
 
interface interface_name{
interface nested_interface_name{
   }
}
 
Syntax

This is declared within the class.
 
class class_name{
interface nested_interface_name{
   }
}
 
Let’s see an example of the nested interface, given below, which is declared within the interface.
 
Code
  1. interface A {  
  2.     void a();  
  3.     interface B {  
  4.         void b();  
  5.     }  
  6. }  
  7. public class NestedInterface implements A.B {  
  8.     public void b() {  
  9.         System.out.println("I am nested interface");  
  10.     }  
  11.     public static void main(String args[]) {  
  12.         A.B obj = new NestedInterface(); //upcasting  
  13.         obj.b();  
  14.     }  
  15. }  
17

Output

18

In the example, mentioned above, we access the B interface by its outer interface A because it cannot be accessed directly.
 
Internal code generated by the compiler for the nested interface B.
 
The compiler internally creates public and static interface, as displayed below.
 
public static interface A$B
{
   public abstract void b();
}
 
Let’s see an example of the nested interface, which is declared within the class.
 
Code
  1. class A {  
  2.     interface B {  
  3.         void b();  
  4.     }  
  5. }  
  6. public class NestedInterface implements A.B {  
  7.     public void b() {  
  8.         System.out.println("I am nested interface");  
  9.     }  
  10.     public static void main(String args[]) {  
  11.         A.B obj = new NestedInterface(); //upcasting  
  12.         obj.b();  
  13.     }  
  14. }  
19

Output

20

We can define a class inside the interface

Yes, if we define a class inside any interface, Java compiler creates a static nested class.
 
How can we define a class within the interface? Let’s see,
 
interface Runable{
class A{}
}
 
Summary

Thus, we learnt that an interface declared within another interface or a class is called a nested interface in Java and also learnt how to create it.