Video in progress

Strong Junior 🧱 OOP and SOLID

Why are `static` and `private` methods in an interface needed, and are they inherited by a class that implements the interface?

static methods (Java 8) are for helpers or factories that belong to the interface, and private methods (Java 9) are for hiding shared code between default methods. Neither is inherited by a class that implements the interface.

📖 Answer

public interface Discount {
    Money apply(Money price);

    static Discount percent(int p) {              // factory
        return price -> price.minusPercent(p);
    }

    default Money applyTwice(Money price) {
        return log(apply(apply(price)));
    }

    private Money log(Money m) {                  // internal helper only
        System.out.println("natija: " + m);
        return m;
    }
}

Discount d = Discount.percent(10);   // correct
// SummerDiscount.percent(10);       // error: an interface static method is not inherited

Why isn't a static method inherited? A class can implement several interfaces, and if both have the same static method, which one would it be? Java avoids this confusion entirely: an interface static method can only be called as Discount.percent(...). That is the difference from a class's static methods, which can also be called through the child class name.

private methods pull out code repeated across default methods without exposing it in the API. They are visible only inside this interface.

Examples from the JDK: List.of(...), Comparator.comparing(...), Map.entry(...) are all interface static methods.