ProgrammingJava Architect

What are static methods in Java interfaces and how do they differ from abstract methods?

Pass interviews with Hintsage AI assistant

Answer

Static methods in interfaces were introduced starting with Java 8. They are declared with the static keyword and implemented directly in the interface. Static methods are not inherited by implementing classes and are called through the interface name.

  • Declaration of a static method:
interface MathUtils { static int sum(int a, int b) { return a + b; } }
  • Calling: MathUtils.sum(1, 2);
  • Static methods of interfaces cannot be overridden in implementing classes.
  • They provide "utility" functions related to the interface, but do not require instance state.
  • Abstract methods must be implemented by the class; static ones do not.

Trick Question

Question: Can a static method of an interface be called through an instance of the implementing class?

Answer: No, the static method of an interface is always called through the interface name, not through an instance or name of the implementing class. The example below will cause a compilation error:

MathUtils utils = new SomeMathUtilsImpl(); utils.sum(1, 2); // Error! Should be MathUtils.sum(1, 2)

Examples of Real Errors Due to Ignorance of the Topic


Story

Developers mistakenly tried to "override" a static method of an interface in the implementing class and expected to call this method through an instance. As a result, the version from the interface was always called, leading to incorrect business logic during use.


Story

When migrating utility methods from a class to an interface, part of the code used calls through an object: obj.method(), which became impossible, requiring refactoring of calls to InterfaceName.method() throughout the project.


Story

Support for older Java versions led to compilation errors after adding static methods to interfaces; developers did not check which version of the compiler was used in CI, and the build began to fail regularly.