What is a Nested Interface in Java?
What is a Nested Interface in Java?
This blog will help you understand what nested interfaces are, why they’re useful, and how they differ from nested classes.
Nested Interface
- A nested interface is an interface that is declared inside another class or interface.
- It is a static interface by default.
- Nested interfaces can be accessed using the outer class or interface name.
- They help logically group interfaces that are only used by their outer class or interface.
- They can be declared public, private, or protected depending on their enclosing class.
Example of Nested Interface
class OuterClass {
interface NestedInterface {
void display();
}
}
class InnerClass implements OuterClass.NestedInterface {
public void display() {
System.out.println("This is a nested interface example.");
}
}
public class Main {
public static void main(String[] args) {
OuterClass.NestedInterface obj = new InnerClass();
obj.display();
}
}
Uses of Nested Interface
- Encapsulation: Groups related interfaces with the classes they belong to.
- Modularity: Keeps the code organized and readable.
- Access Control: Provides the ability to restrict access to the interface.
- Namespace Management: Prevents name clashes by placing the interface in a specific scope.
Difference between Nested Interface and Nested Class
Nested Interface | Nested Class | |
---|---|---|
Definition | An interface declared inside a class or interface. | A class declared inside another class. |
Type | Always static by nature. | Can be static or non-static (inner class). |
Implementation | Implemented by a class using OuterClass.InterfaceName syntax. | Instantiated using the outer class object (if non-static). |
Use Case | To define a contract specific to the outer class or interface. | To group helper classes or for logic encapsulation. |
Inheritance | Only methods — no concrete behavior. | Can have fields and concrete methods. |