Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeNested Interface Inside Another Interface in Java
In Java, a nested interface is an interface declared within another interface or class. Declaring an interface inside another interface helps you group related interfaces together so your codebase stays organized and easy to maintain.
Just like an interface nested inside a class, a nested interface inside another interface cannot be accessed directly—it must always be referenced through the outer interface.
How to Implement a Nested Interface Inside an Interface
Follow these steps when working with an interface nested inside another interface:
- Declare the Nested Interface: Define
NestedInterfaceinsideOuterInterface. - Implement Using Dot Notation: In your implementing class, use
implements OuterInterface.NestedInterface. - Provide the Method Implementation: Implement the abstract method declared inside
NestedInterface.
Code Example: Java Nested Interface Inside an Interface
public interface OuterInterface {
void outerMethod();
interface NestedInterface {
void nestedMethod();
}
}
public class MyClass implements OuterInterface.NestedInterface {
public void nestedMethod() {
System.out.println("Nested interface method implemented");
}
}
public class InterfaceTest {
public static void main(String[] args) {
OuterInterface.NestedInterface ref = new MyClass();
ref.nestedMethod();
}
}
void outerMethod();
interface NestedInterface {
void nestedMethod();
}
}
public class MyClass implements OuterInterface.NestedInterface {
public void nestedMethod() {
System.out.println("Nested interface method implemented");
}
}
public class InterfaceTest {
public static void main(String[] args) {
OuterInterface.NestedInterface ref = new MyClass();
ref.nestedMethod();
}
}
Key Takeaways
- Implicitly Public & Static: Any interface declared inside another interface is implicitly
publicandstatic. - Independent Implementation: Implementing
OuterInterface.NestedInterfaceonly requires implementing the nested interface's methods, notOuterInterface's methods. - Qualified Reference: Always refer to the nested interface using
OuterInterface.NestedInterface.
No comments:
Post a Comment