Java 8-Java CoreNo Comments

Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8. For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.

Syntax

Multiple Defaults

With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved.

First solution is to create an own method that overrides the default implementation.

Second solution is to call the default method of the specified interface using super.

Static Default Methods

An interface can also have static helper methods from Java 8 onwards.

Default Method Example

Let’s see an example to get more clarity on default method. Please write the following program in an code editor, understand and verify the results.

Java8Tester.java

Verify the Result

Compile the class using javac compiler as follows −

Now run the Java8Tester as follows −

It should produce the following output −


Be the first to post a comment.

Add a comment