Nested Interface

Author: Ravi Poswal

An interface is known as the blueprint of a class because it defines a set of abstract methods that a class must implement. When an interface is declared inside another interface or a class, it is called a nested interface. Nested interfaces help in organizing and grouping related functionalities in a structured way. They can use different access modifiers such as public, private, protected, and default, depending on where they are declared. This feature improves encapsulation and makes the program more modular and easy to manage. There are two types of nested interfaces in Java.

1. Interface inside of the class

When an interface is declared inside of the class is called nested interface. 

Code Example

class Card {
    interface debit {
        void display1();
    }
  interface credit {
        void display2();
    }
}

class Account implements Card.debit, Card.credit 
{
        public void display1()
{      
        System.out.println("this is the Ranrev");
    }
    public void display2()
{      
        System.out.println("hello Ranrev");
    }

    public static void main(String[] args){
        
        Card.debit obj = new Account();
    Card.credit obj1 = new Account();
        obj.display1();
obj1.display2();
    }
}

1. Interface inside of the another interface

When an interface is declared inside other interface is called nested interface.

Code Example

interface Outer {
    interface Inner {
        void show();
    }
}
class Test implements Outer.Inner 
{  
    public void show() {
        System.out.println("This is nested interface inside another interface");
    }

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

FAQs

A nested interface in Java is an interface that is declared inside another interface or class. It is used to logically group related interfaces and improve code organization. Nested interfaces are implicitly static, meaning they can be accessed without creating an object of the outer type.

Yes, Java allows declaring an interface inside another interface. Such an interface is called a nested interface and is public and static by default.

A nested interface is accessed using the outer interface name followed by the inner interface name.
Outer.Inner obj;

Yes, a class can implement a nested interface by using the syntax:
class Test implements Outer.Inner {
public void show() {
System.out.println("Implemented nested interface");
}
}

Improves code organization
Provides better encapsulation
Helps group related functionality
Useful in large applications

No, it is not required because nested interfaces are static by default.

Nested interfaces are commonly used in:

Event handling
Callbacks
API design
Large-scale software systems