Friday, 15 January 2016

Java Tutorial : Java Nested Interface(Inside Interface)

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

Nested 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 NestedInterface inside OuterInterface.
  • 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();
  }
}

Key Takeaways

  1. Implicitly Public & Static: Any interface declared inside another interface is implicitly public and static.
  2. Independent Implementation: Implementing OuterInterface.NestedInterface only requires implementing the nested interface's methods, not OuterInterface's methods.
  3. Qualified Reference: Always refer to the nested interface using OuterInterface.NestedInterface.

Watch More Java Tutorials:

No comments:

Post a Comment

Tutorials