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

Henrik Paul picture Henrik Paul · Aug 22, 2008 · Viewed 103.1k times · Source

The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?

public interface ITest {
    public static String test();
}

The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".

Answer

James A. Rosen picture James A. Rosen · Aug 22, 2008

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!