Starting with Java 8, interfaces can define default method implementations.
As of Java 8, whenever you have the choice of either, you should go with the defender (aka. default) method in the interface.
Interface Default method advantage
The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation’s state. So the main use case is higher-level and convenience methods.
The good thing about this new feature is that, while before you were forced to use an abstract class for the convenience methods, thus constraining the implementer to single inheritance, now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer.
You can read more on Default Interface Method here :
Are the abstract classes still useful?
Abstract classes can still do more in comparison to Java 8 interfaces:
- Abstract class can have a constructor. The interface has no constructors to be invoked by the descendants
- Abstract classes are more structured and can hold a state.
In comparison, Interface methods are all public, field members are all constants (final & public). You may want to restrict access privileges of methods and/or make them operate on non-constant state.
- Type clarity:
You can only extend one class. This makes it clearer what your object is and how to use it.
When should interface with default methods be used and when should an abstract class be used?
Which should you use, abstract classes or interfaces?
From Oracle documentation :
Consider using abstract classes if any of these statements apply to your situation:
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- You want to take advantage of multiple inheritance of type.
You may also like :
© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post