Sunday, 3 September 2017

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



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



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!


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...