Course contentsShow
← Java
Lesson 504 of 2,87012. Abstract Classes and InterfacesFree lesson

Practical Example: Multiple Capability Interfaces

Implement a class with Serializable, Comparable, and Closeable to see real-world multiple interface usage.

Practical Example: Multiple Capability Interfaces

You'll learn how a single class can implement multiple unrelated interfaces to gain distinct capabilities, just like real JDK classes do.

The Idea: Mixing Capabilities

In real-world Java, classes often implement multiple interfaces to signal they possess different capabilities. Think of it like a Swiss Army knife—one tool with multiple functions. A class might be serializable (savable to disk), comparable (sortable), and closeable (cleanup-aware) all at once.

Each interface represents an independent contract. By implementing all three, your class advertises: "I can be saved, sorted, and cleaned up."

Code Example

import java.io.*;

public class UserSession implements Serializable, Comparable<UserSession>, Closeable {
    private String username;
    private int loginCount;

    public UserSession(String username, int loginCount) {
        this.username = username;
        this.loginCount = loginCount;
    }

    // From Serializable (marker interface - no methods required)

    // From Comparable
    @Override
    public int compareTo(UserSession other) {
        return Integer.compare(this.loginCount, other.loginCount);
    }

    // From Closeable
    @Override
    public void close() throws IOException {
        System.out.println("Logging out: " + username);
        // Cleanup resources here
    }

    public String getUsername() {
        return username;
    }
}

How It Works

  • Serializable: Marker interface; signals this object can be converted to bytes and saved.
  • Comparable<UserSession>: Requires compareTo() so sessions can be sorted by login count.
  • Closeable: Requires close() for resource cleanup (e.g., closing network connections).

Each capability is independent. Code expecting a Comparable can sort your sessions. Code expecting Closeable can clean them up. Same class, multiple roles.

Key Takeaway:
Implementing multiple interfaces lets one class fulfill several contracts, making it flexible and reusable across different contexts—a core Java design pattern.