Sobes.tech
Middle

What is a static method of an interface?

sobes.tech AI

Answer from AI

A static method in an interface is a method defined within the interface using the static keyword.

Features:

  • It is not associated with a specific instance of the implementing class.
  • It is called directly from the interface itself.
  • It has a method body, unlike regular abstract interface methods (before Java 8).
  • It allows adding auxiliary or utility methods to the interface without requiring their implementation in classes.

Example:

interface MyInterface {

    // Static method of the interface
    static void staticMethod() {
        System.out.println("This is a static method of the interface");
    }

    // Abstract method
    void instanceMethod();
}

// Implementing class
class MyClass implements MyInterface {

    @Override
    public void instanceMethod() {
        System.out.println("This is an instance method of the class");
    }
}

// Usage
class Main {
    public static void main(String[] args) {
        MyInterface.staticMethod(); // Calling static method via interface

        MyClass obj = new MyClass();
        obj.instanceMethod(); // Calling instance method
    }
}
What is a static method of an interface? — Java - sobes.tech