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.
interface MathUtils { static int sum(int a, int b) { return a + b; } }
MathUtils.sum(1, 2);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)
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 toInterfaceName.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.