Default Methods In Java

Default methods enables us to add new functions to our existing interfaces. This ensures binary compatibility with code written for older versions of those interfaces.

Put it simply, default methods allows us to provide default implementations of methods in the interface itself.

Syntax – Default Methods

To specify that a method definition in an interface is a default method, add keyword default to the method signature. Method declarations in an interface, including default methods, are implicitly public, so no need to add public modifier.

interface SomeInterface {
  default methodName() {
    //some implementation
   }
}

Let us look at an example to understand this better. Imagine, you have provided a library providing the functionality of a RemoteControl.

This is exposed to the clients, using an interface RemoteControl and has methods play, stop and pause.

Now, you want to release a new version, providing the recording feature and you want to add a new method record to the same interface. Those clients capable of using the record function can call it, others can ignore it.

But you know the problem, if we add another method to the interface, it breaks the clients code. As a result, they will get exception complaining that the code didn’t implement the record method and program will fail. This is something we can prevent by using the default methods.

package com.stackrules.java;

/**
 * Example showcasing the default methods
 */
public class DefaultMethodExample implements RemoteControl{

    public static void main(String[] args) {
            RemoteControl remote =new DefaultMethodExample();
            remote.play();
            remote.stop();
    }
    @Override
    public void play() {
        System.out.println("Play");
    }
    @Override
    public void stop() {
        System.out.println("Stop");
    }
    @Override
    public void pause() {
        System.out.println("Pause");
    }
}
/**
 * Providing the remote control operations
 */
interface RemoteControl {
    void play();
    void stop();
    void pause();
   //adding a default implementation for record
     default void record() {
        System.out.println("recording");
    }
}

In the above example, we have provided a default implementation for our new method, record. Old clients will continue to work as their interface won’t break. They can invoke the record method if they wish to use the default implementation. When they are ready to implement the record functionality, they can override and provide an implementation. This is the whole idea of default methods in interfaces

Leave a Comment