What are Default Methods in Java 8?

Java 8Object Oriented ProgrammingProgramming

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

In a separate class you need to implement this interface and provide body for all its abstract methods.

Example

 Live Demo

interface MyInterface{
   public void demo();
}
public class InterfaceExample implements MyInterface{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      new InterfaceExample().demo();
   }
}

Output

This is the implementation of the demo method

If a new method is added to an interface, you need to provide body for this method in all the classes implementing its interface

Default method

From JSE8 Default methods are introduced in Java. Since then, you can write a default implementation to a particular method in an interface. If you do so, there is no need to implement these (default methods) in the classes that already implement this interface.

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");
}

Note − All the methods of an interface are public therefore there is no need to use public before it explicitly.

Example

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

 Live Demo

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
raja
Published on 03-Jul-2019 17:55:12
Advertisements