Wednesday, 13 January 2016

Java Tutorial : Nested class in Interface

Master Core Java Step-by-Step!

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

Subscribe Now on YouTube

Nested Class Implementation Inside a Java Interface

In Java, interfaces are widely known for holding abstract methods, default methods, and static methods. However, many developers don't realize that an interface can also contain nested classes.

Defining a class directly inside an interface is a powerful technique for packaging default implementations, data structures, or helper classes tightly with the contract they support.

Why Define a Class Inside an Interface?

Placing a nested class within an interface offers clean architectural advantages:

  • Logical Grouping: If a class is solely intended to work with or provide a reference implementation for an interface, grouping them together improves readability.
  • Default or Reference Implementation: An interface can bundle a complete, ready-to-use implementation of itself directly within its declaration.
  • Clean Encapsulation: Helper data models or transfer objects (DTOs) tied exclusively to an interface contract stay localized and organized.

Code Example: Implementing an Interface's Nested Class

interface Vehicle {
  void drive();

  // Nested class defined directly inside an interface
  class DefaultCar implements Vehicle {
    public void drive() {
      System.out.println("Driving the default vehicle implementation.");
    }
  }
}

public class Test {
  public static void main(String[] args) {
    // Instantiating the nested class using InterfaceName.ClassName
    Vehicle vehicle = new Vehicle.DefaultCar();
    vehicle.drive();
  }
}

Output:

Driving the default vehicle implementation.

Key Rules for Nested Classes in Interfaces

  1. Implicitly Public and Static: Any class declared inside an interface is automatically public and static, even if you omit those keywords.
  2. Can Implement the Enclosing Interface: A nested class inside an interface can freely implement its enclosing interface to serve as a default implementation.
  3. Direct Instantiation: Because it is static by default, you can instantiate it directly using new OuterInterface.InnerClass() without needing an instance of the interface.

Watch More Java Nested Class & Interface Tutorials:

No comments:

Post a Comment

Tutorials