#
"static" method in an interface
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.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
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
Info
As you can see, now you can add a static method to an interface starting from Java 8.
If you want, you can take a look at the article named Default methods in Java interfaces.