What is default method in java interfaces?

1. Until 1.7 version inside interface we can declare only public abstract methods and public static final variables, concrete methods are not allowed.

2. But from Java 1.8 version on wards in addition to these, we can declare default concrete methods also inside interface, which are also known as defender methods.

3. Default methods are allowed only in interfaces.

We can declare default method with the keyword “default” as follows:

Use of default method in java interfaces

 1. Any class that implements an interface must provide an implementation for each method defined by the interface or inherit the implementation from a super class, but Default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface. Default methods also known as defender methods or virtual extension methods.

2. The main advantage of default methods is without effecting implementation classes we can add new functionality to the interface (backward compatibility).

3. Interface default methods are by default available to all implementation classes. An implementation class can use these default methods directly or can override.

Example 1

Example 2

Interface with default methods vs abstract class

Even though we can add concrete methods in the form of default methods to the interface , interface are not equal to abstract classes.

Interface with Default Methods Abstract Class
Inside interface every variable is always public static final and there is no chance of instance variables Inside abstract class we can declare instance variables which Are required to the child class.
Inside interface we can’t declare constructors. Inside abstract class we can declare constructors.
Inside interface we can’t declare instance and static blocks. Inside abstract class we can declare instance and static blocks.
Functional interface with default methods can refer lambda expression. Abstract class can’t refer lambda expressions.
Inside interface we can’t override Object class methods. Inside abstract class we can override Object class methods.