Java 8 interfaces: default methods for backwards compatibility

Ben Weidig
Feb 1, 2017 · 2 min read

Another new addition to the Java repertoire are default methods for interfaces: implement a method directly in the interface instead of a class implementing that interface needing to override it. You can still override it, but you don’t have too.

Problem: backwards compatibility

Imagine the following (simplified) interface for a list:

public interface List {
void add(Object obj);
Object get(int index);
boolean isEmpty();
}

In a typical project we might implement several list types with this interface, and now we have a great idea: more functionality!

public interface List {
// Old methods
void add(Object obj);
Object get(int index);
boolean isEmpty();
// New methods
Object first();
void sort();
}

An addition to the interface would mean we just broke the contract the interface declares, resulting in incompatibility with every class that implemented the interface, which means a lot of work to fix it. The incompatibility issue is even more relevant if someone other than us is relying on our interface in their projects. With default methods we can avoid these issues!

Solution: default methods

Instead of implementing the two new methods on every implementation of List we provide an implementation directly on the interface:

public interface List {
// Old methods
void add(Object obj);
Object get(int index);
boolean isEmpty();
// New methods
default Object first() {
if (isEmpty()) {
return null;
}
return get(0);
}
default void sort() {
throw new UnsupportedOperationException();
}
}

This example shows the two ways you could and should use default methods for backwards compatibility:

  • Implementing new functionality that is common for most of the classes (first())
  • Throwing an exception to indicate you NEED to implement a certain feature yourself (sort())

Conclusion

Default methods are a great way to ensure backwards compatibility in your projects, and might even save you writing the same code over and over again. You only have access to the interface methods, so you can’t implement much functionality. But sometimes (like in our example) it’s enough.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade