Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeWhat Is a Nested Interface in Java?
In Java, an interface declared inside another class or another interface is known as a nested interface. Nested interfaces are commonly used to group related interfaces together so that your code is cleaner, more organized, and easier to maintain.
Because a nested interface is scoped to its enclosing type, you can't access it directly—it must always be referred to using the outer class or outer interface name.
How to Implement a Nested Interface Inside a Class
When you declare an interface inside an outer class, any class that implements it must reference it through the outer class:
- Declare the Nested Interface: Define the interface inside your outer class (for example,
NestedInterfaceinsideOuterClass). - Implement Using Dot Notation: Your implementing class uses
implements OuterClass.NestedInterface. - Provide Method Implementations: Implement all abstract methods declared inside the nested interface.
Code Example: Java Nested Interface Inside a Class
public class OuterClass {
public interface NestedInterface {
void nestedMethod();
}
public void outerMethod() {
System.out.println("Outer class method");
}
}
public class MyClass implements OuterClass.NestedInterface {
public void nestedMethod() {
System.out.println("Nested interface method implemented");
}
}
public class InterfaceTest {
public static void main(String[] args) {
OuterClass.NestedInterface ref = new MyClass();
ref.nestedMethod();
}
}
public interface NestedInterface {
void nestedMethod();
}
public void outerMethod() {
System.out.println("Outer class method");
}
}
public class MyClass implements OuterClass.NestedInterface {
public void nestedMethod() {
System.out.println("Nested interface method implemented");
}
}
public class InterfaceTest {
public static void main(String[] args) {
OuterClass.NestedInterface ref = new MyClass();
ref.nestedMethod();
}
}
Key Takeaways
- Logical Grouping: Nested interfaces keep closely related contracts grouped inside a single outer class or interface.
- Qualified Access: Always reference the nested interface using
OuterClass.NestedInterface. - Polymorphic References: You can hold an instance of the implementing class using a
OuterClass.NestedInterfacereference variable.
No comments:
Post a Comment