Computer >> Computer tutorials >  >> Programming >> Java

What is the use of default methods in Java?


An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

  • It is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
  • If you need your class to follow a certain specification you need to implement the required interface and provide body for all the abstract methods in that interface.
  • If you do not provide the implementation of all the abstract methods of an interface (you, implement) a compile time error is generated.

What if new methods are added in the interfaces?

Suppose we are using certain interface and implemented all the abstract methods in that interface and new methods were added later. Then, all the classes using this interface will not work unless you implement the newly added methods in each of them.

To resolve this issue from Java8 default methods are introduced.

Default methods

A default method is also known as defender method or virtual extension method. You can define a default method using the default keyword as −

default void display() {
   System.out.println("This is a default method");      
}

Once write a default implementation to a particular method in an interface. there is no need to implement it in the classes that already using (implementing) this interface.

Following Java Example demonstrates the usage of the default method in Java.

Example

interface sampleInterface{  
   public void demo();  
   default void display() {
      System.out.println("This is a default method");      
   }
}
public class DefaultMethodExample implements sampleInterface{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }  
   public static void main(String args[]) {      
      DefaultMethodExample obj = new DefaultMethodExample();
      obj.demo();
      obj.display();      
   }
}

Output

This is the implementation of the demo method
This is a default method