Video in progress

You need to add a new method to an interface in a Java library used by many teams. How do you do it without breaking users?

public interface Notifier {
    void send(String to, String text);
}
// needed in v2: send(to, text, priority)

I add a default method to the interface or create a new small interface. I check binary and source compatibility separately (with japicmp or revapi), mark what will be removed @Deprecated(forRemoval = true) first, and remove it in a major version under semver.

📖 Answer

If you add an abstract method, every class that implements Notifier stops compiling. Code running against the old jar gets an AbstractMethodError at runtime, the moment the new method is called.

Option 1: a default method:

public interface Notifier {
    void send(String to, String text);

    default void send(String to, String text, Priority p) {
        send(to, text);   // acceptable behavior for old implementations
    }
}

This is source and binary compatible. Where to be careful: if some implementation already has a method with the same signature, or the same default is inherited from two interfaces, you get a conflict.

Option 2: a new interface: PriorityNotifier extends Notifier. The caller checks with instanceof. If there's no "acceptable default behavior", this is more honest.

A few more rules:

  • Check compatibility automatically: the japicmp/revapi Maven plugin finds breaking changes against the previous release and fails the build.
  • Input types and return types are different. Widening a parameter type may be source-compatible but not binary-compatible, because the method descriptor changes.
  • Adding a value to an enum: a user's exhaustive switch didn't expect the new value.
  • The deprecation cycle: @Deprecated(since = "2.3", forRemoval = true), a warning for at least one minor release, then removal in a major release.
  • Hide internal classes from the start (package-private, JPMS exports), so they never turn into a contract.