Java 8 Interfaces: default methods for backward compatibility

Ben Weidig
2 min readFeb 1, 2017
Photo by Mike Kenneally on Unsplash

Another new addition to the Java repertoire are default methods for interfaces: Write a non-abstract method directly in the interface instead of its implementation. You can still override it, but you don’t have too.

Problem: backward 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

--

--

Ben Weidig

Software developer, entrepreneur, blogger. Mostly Java, sometimes Swift, Golang, Bash and all the other fun stuff.