Java – Why were default and static methods added to interfaces in Java 8 when we already had abstract classes

interfacesjavajava8programming-languages

In Java 8, interfaces can contain implemented methods, static methods, and the so-called "default" methods (which the implementing classes do not need to override).

In my (probably naive) view, there was no need to violate interfaces like this. Interfaces have always been a contract you must fulfill, and this is a very simple and pure concept. Now it is a mix of several things. In my opinion:

  1. static methods do not belong to interfaces. They belong to utility classes.
  2. "default" methods shouldn't have been allowed in interfaces at all. You could always use an abstract class for this purpose.

In short:

Before Java 8:

  • You could use abstract and regular classes to provide static and default methods. The role of interfaces is clear.
  • All the methods in an interface should be overriden by implementing classes.
  • You can't add a new method in an interface without modifying all the implementations, but this is actually a good thing.

After Java 8:

  • There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.
  • When programming the implementations, programmers may forget to override the default methods.
  • There is a compilation error if a class tries to implement two or more interfaces having a default method with the same signature.
  • By adding a default method to an interface, every implementing class automatically inherits this behavior. Some of these classes might have not been designed with that new functionality in mind, and this can cause problems. For instance, if someone adds a new default method default void foo() to an interface Ix, then the class Cx implementing Ix and having a private foo method with the same signature does not compile.

What are the main reasons for such major changes, and what new benefits (if any) do they add?

Best Answer

A good motivating example for default methods is in the Java standard library, where you now have

list.sort(ordering);

instead of

Collections.sort(list, ordering);

I don't think they could have done that otherwise without more than one identical implementation of List.sort.