Kong Kong - 1 year ago 83
Java Question

Java 8: virtual extension methods vs abstract class

I'm looking at the new virtual extension methods in Java 8 interfaces:

public interface MyInterface {
default String myMethod() {
return "myImplementation";

I get their purpose in allowing an interface to evolve over time, and the multiple inheritance bit, but they look awfully like an abstract class to me.

If you're doing new work are abstract classes prefered over extension methods to provide implementation to an "interface" or are these two approaches conceptually equivalent?

Answer Source

One primary purpose of such constructs is to preserve backwards compatibility. The addition of closures to the Java language is quite a major alteration, and things need to be updated to fully take advantage of this. For example, Collection in Java 8 will have methods such as forEach() which work in conjunction with lambdas. Simply adding such methods to the pre-existing Collection interface would not be feasible, since it would break backwards compatibility. A class I wrote in Java 7 implementing Collection would no longer compile since it would lack these methods. Consequently, these methods are introduced with a "default" implementation. If you know Scala, you can see that Java interfaces are becoming more like Scala traits.

As for interfaces vs abstract classes, the two are still different in Java 8; you still can't have a constructor in an interface, for example. Hence, the two approaches are not "conceptually equivalent" per se. Abstract classes are more structured and can have a state associated with them, whereas interfaces can not. You should use whichever makes more sense in the context of your program, just like you would do in Java 7 and below.