A nested interface is an interface declared inside a class or another interface. It helps group related interfaces and organize code.
- Nested interfaces are implicitly static.
- Their accessibility depends on where they are declared.
Types of Nested Interfaces
Nested interfaces are classified into two types based on their declaration location.
1. Nested Interface Inside a Class
An interface declared inside a class can have public, protected, private, or package-private access.
- It is accessed using OuterClass.InnerInterface.
- Its access modifier controls where it can be used.
class Outer{
interface Inner{
void display();
}
}
class Geeks implements Outer.Inner{
public void display(){
System.out.println("Hello from Inner");
}
public static void main(String[] args){
Outer.Inner obj = new Geeks();
obj.display();
}
}
Output
Hello from Inner
Explanation: The Geeks class implements the nested interface using Outer.Inner and provides the implementation of the display() method.
2. Nested Interface Inside an Interface
An interface declared inside another interface is implicitly public and static.
- It is accessed using OuterInterface.InnerInterface.
- A class can implement the nested interface without implementing the enclosing interface.
interface Outer{
interface Inner{
void display();
}
}
class Geeks implements Outer.Inner{
public void display(){
System.out.println("Hello from Inner");
}
public static void main(String[] args){
Outer.Inner obj = new Geeks();
obj.display();
}
}
Output
Hello from Inner
Explanation: The Geeks class implements Outer. Inner without implementing the enclosing Outer interface.
Access Rules for Nested Interfaces
The allowed access modifiers depend on the declaration location.
Declaration Location | Allowed Access |
|---|---|
Inside a class | public, protected, private, package-private |
Inside an interface | public |
Outside a class or interface | public, package-private |
Declaring a nested interface as private or protected inside another interface causes a compilation error.
Uses of Nested Interfaces
- Groups contracts with their related classes or interfaces.
- Restricts accessibility when declared inside a class.
- Prevents naming conflicts through separate scopes.
- Defines callbacks and event-handling contracts.