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

Private Instance Methods in Interfaces

Learn to define private instance methods that can be called by default methods to extract common logic.

Private Instance Methods in Interfaces

What you'll learn: How to use private instance methods inside interfaces to share logic between default methods, making your code cleaner and more maintainable.


The Core Idea

As you've seen, interfaces can have default methods that provide implementations. Sometimes, multiple default methods need to share common logic. Instead of duplicating code, Java 9 introduced private instance methods in interfaces—helper methods that can be called by default methods but remain hidden from implementing classes.

Think of it like kitchen recipes: the public recipes (default methods) are what guests see, but chefs use private techniques (private methods) behind the scenes to avoid repeating steps in multiple recipes.

Syntax and Usage

public interface Logger {
    // Private instance method to extract common logic
    private String formatMessage(String level, String message) {
        return "[" + level + "] " + message;
    }
    
    // Default methods calling the private method
    default void logInfo(String message) {
        System.out.println(formatMessage("INFO", message));
    }
    
    default void logWarning(String message) {
        System.out.println(formatMessage("WARNING", message));
    }
}

Key Rules

  • Private instance methods can only be called by default methods (or other private methods) in the same interface
  • They cannot be called by static methods in the interface
  • They cannot be accessed by implementing classes
  • They help reduce duplication between default methods

Why This Matters

Before private instance methods, you had two bad choices: duplicate logic across multiple default methods, or make helper methods public (exposing internal details). Private instance methods give you the best of both worlds—code reuse without polluting the public API.

Key Takeaway: Private instance methods let default methods share common logic internally, keeping interfaces clean and avoiding code duplication.