Default Method in Java Interface Tutorial

In this section, we will learn what the interface default method is and how to use it in Java.

Note: Also, in this section we’re assuming you’re already familiar with interfaces.

What Is Default Method in Java Interface?

We know that inside an interface we use abstract methods because we want all the classes that implement the interface override these methods and set their own version of the body for each method.

On the other hand, there might be one or more methods in an interface that pretty much any class that implements the interface will use the same body for those methods. In such case, instead of turning those methods into abstract, we can set them as default methods.

A default method, unlike abstract methods, has its own body inside an interface. Later on, when implementing the interface on a class, we can use these default methods without the need of overriding. Of course, we can still override such methods, but that would be optional.

How to Define Default Method in Java Interface?

In order to create a default method in an interface, we need to use the keyword `default` before the data type of the method.

Example: creating default method in Java interface

public interface FirstInterface {

    default void sayHi(){
        System.out.println("Hello from a default method");
    }
}

In this interface, the `sayHi()` method is default because it started with the keyword `default` and it has a body.

Now let’s implement this interface on a class named `SClass`:

public class SClass implements FirstInterface {
}

As you can see, the `SClass` implemented the interface but didn’t override the `sayHi()` method.

Example: invoking default method of Java interface

Now we can simply create an object from the `SClass` and call the `sayHi()` method:

public class Simple {
    public static void main(String[] args) {
        FirstInterface firstInterface = new SClass();
        firstInterface.sayHi();
    }
}

Output:

Hello from a default method

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies