JavaJava 8

Java 8 interface new features

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.

 

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.

 

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.

 

Functional interfaces

A functional interface is an interface with only one abstract method.

 

For example, Comparator is a functional interface with only one method compare().

 

 

 

© 2015, www.techkatak.com. All rights reserved.

One thought on “Java 8 interface new features

Comments are closed.