0
0
Javaprogramming~5 mins

Static methods in interfaces in Java

Choose your learning style9 modes available
Introduction

Static methods in interfaces let you add helper functions directly inside the interface. This keeps related code together and easy to find.

When you want to provide utility methods related to the interface without needing an object.
When you want to group helper functions that belong to the interface's concept.
When you want to avoid creating separate utility classes for simple static methods.
When you want to keep interface-related code organized in one place.
Syntax
Java
public interface InterfaceName {
    static ReturnType methodName(Parameters) {
        // method body
    }
}

Static methods in interfaces must have a body (implementation).

You call static methods on the interface name, not on instances.

Examples
This interface has a static method add that adds two numbers.
Java
public interface Calculator {
    static int add(int a, int b) {
        return a + b;
    }
}
Call the static method add using the interface name Calculator.
Java
int sum = Calculator.add(5, 3);
Sample Program

This program defines an interface Printer with a static method printHello. The Main class calls this method directly from the interface.

Java
public interface Printer {
    static void printHello() {
        System.out.println("Hello from static method in interface!");
    }
}

public class Main {
    public static void main(String[] args) {
        Printer.printHello();
    }
}
OutputSuccess
Important Notes

Static methods in interfaces cannot be overridden by implementing classes.

They help keep utility methods close to the interface's purpose.

Summary

Static methods in interfaces provide helper functions related to the interface.

They are called using the interface name, not instances.

This feature helps organize code and avoid extra utility classes.