# "static" method in an interface

In 
Published 2022-12-03

This tutorial explains to you how to use a static methods 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:

package com.example.demo;

public interface MyInterface {

    // static method
    static void sayHelloStatic(){
        System.out.println("Hello John, from the static method");
    }

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

public class SayHello implements MyInterface{

    public void sayHelloAbstract(String helloMessage) {
         System.out.println("Hello "+ helloMessage+ ", from the abstract method");
    }
}
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 static method from the interface
		MyInterface.sayHelloStatic();

		//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 static 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 Default methods in Java interfaces.