# "default" method in an interface

In 
Published 2022-12-03

This tutorial explains to you how to use a default method in a Java interface.

Before Java 8 this feature wasn't available.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

From the base application downloaded from Spring Initializr, I updated the main class and added the following classes/interface as below:

MyInterface.java
package com.example.demo;

public interface MyInterface {

    // Default method
    default void sayHelloDefault(){
        System.out.println("Hello John, from the default method");
    }

    // Abstract method
    void sayHelloAbstract(String helloMessage);
}
SayHello.java
package com.example.demo;

public class SayHello implements MyInterface{

  public void sayHelloAbstract(String helloMessage) {
    System.out.println("Hello "+ helloMessage+ ", from the abstract method");
  }
}
DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.time.*;
import java.time.temporal.ChronoField;

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {

    SpringApplication.run(DemoApplication.class, args);

    SayHello sayHello = new SayHello();

    //Using the default method from the interface
    sayHello.sayHelloDefault();

    //Using the method which was implemented outside the interface
    sayHello.sayHelloAbstract("Anna");
  }
}

When you run, you will get the following result :

Hello John, from the default method
Hello Anna, from the abstract method

Process finished with exit code 0

If you want, you can take a look at the article named Static methods in Java interfaces.