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?
If you want to write an API that allows the user to use lambda expressions, you should use interfaces instead.
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 asforEach()
which work in conjunction with lambdas. Simply adding such methods to the pre-existingCollection
interface would not be feasible, since it would break backwards compatibility. A class I wrote in Java 7 implementingCollection
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 Javainterface
s are becoming more like Scalatrait
s.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.
Abstract classes hold state (instance fields), in order to provide some common behavior (methods).
You don't typically (ever?) see an abstract class without state.
Interfaces specify functionality. They are meant to declare behavior as a contract, not implement it.
Thus any methods that are specified as part of an interface are "helper" methods -- they don't affect the implementation.
Abstract classes scores over
java-8
interfaces in below areas.With abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public
Mutable state can be shared/modified with child classes unlike interface which have only constants
Difference between Abstract class & functional interface are many like all the difference between a normal interface and abstract class but measure difference is we can have default methods in functional interface but not in abstract class, this changes and helped all the collection implementation in java 8 foreach() and other performance method with use of lambda