Why can't I declare static methods in an interface? Why can't I declare static methods in an interface? java java

Why can't I declare static methods in an interface?


There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between

public interface Foo {  public static int bar();}

and

public interface Foo {  public static int bar() {    ...  }}

The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.

Java could allow the latter; and in fact, starting in Java 8, it does!


The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.


I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:

Math.add(2, 3);

If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.