Default Method in Java 8

Overview

Java introduces the default method in Java 8, In this article, we will understand the requirement of the default method in Java.

Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added to an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

Example

interface DefaultExample 
{ 
	// abstract method 
	public void display(int a); 

	// default method 
	default void show() 
	{ 
	System.out.println("Executing Default Method"); 
	} 
} 

class MyClass implements DefaultExample 
{ 
	// implementation of display abstract method 
	public void display(int a) 
	{ 
		System.out.println(2*a); 
	} 

	public static void main(String args[]) 
	{ 
		MyClass m = new MyClass(); 
		m.display(4); 

		// default method executed 
		m.show(); 
	} 
} 

Do we really need an abstract class if we have a default method in Java 8? 

Interface can have only public final constants , If we need to define variable, it is not possible using inteface, we need abstract class for that.

The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods.

For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such a method will simply break the collection framework implementations. Java 8 introduces a default method so that the List/Collection interface can have a default implementation of the forEach method, and there is no need to implement these methods in underlying child classes like ArrayList, HashSet, etc.