In this article, we will discuss about new features added in Java 8 Interfaces.
Default interface methods
Prior to Java 8, an Interface could only have public abstract methods.
The implementing class for this interface was supposed to provided implementation for each of the abstract methods or declare itself as abstract.
With Java 8, an Interface can also contain public default methods with concrete implementations.
An implementing class for such as interface also inherits the default method. It may choose to override the default method, but it’s not necessary.
With this feature, an interface with default methods can replace abstract class in the class hierarchy as the interface itself can contain default concrete methods.
Read more on default interface methods here.
Multiple inheritance with default methods
A class can implement multiple interfaces. So, what will happen if one class inherits the same default method from two unrelated interfaces?
The class must override that method; else, the compiler won’t know which default method to use.
Here is a puzzle on multiple inheritance with default interface method that you may like :
Static interface methods
The default concrete methods in an Interface can be static too. So, they can be used as helper methods. So, there is no need for creating separate helper classes.
For example, for collection interfaces like List, Set etc, a class Collections is provided that provides sort() method. This can instead directly be part of the Interface.
Read more on Static interface methods here.
A functional interface is an interface with only one abstract method.
For example, Comparator is a functional interface with only one method compare().
Read more on functional interface here
You may also like :
© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post