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

105,800

Solution 1

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!

Solution 2

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.

Solution 3

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.

Solution 4

The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:

public class A {
   public method x() {...}
}
public class B {
   public method x() {...}
}
public class C extends A, B { ... }

Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.

Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:

public interface A {
   public static method x() {...}
}
public interface B {
   public static method x() {...}
}
public class C implements A, B { ... }

Same problem here, what happen if you call C.x()?

Solution 5

Static methods are not instance methods. There's no instance context, therefore to implement it from the interface makes little sense.

Share:
105,800

Related videos on Youtube

Henrik Paul
Author by

Henrik Paul

Currently programming mainly in PHP in the spare time, but writing Java for a living. Started writing 5-liners of BASIC on a C64 when I was about 6, and hooked in programming ever since.

Updated on July 08, 2022

Comments

  • Henrik Paul
    Henrik Paul almost 2 years

    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".

    • Mnementh
      Mnementh over 15 years
      Please unaccept Espo's answer, as it is flawed. An interface has a class-file that could contain the implementation of a static method (if the Java-designer would allow this), so there is no problem in resolving the implementation of the static method. It works exactly as with other static classes.
    • Maverick
      Maverick over 10 years
      i kind of agree with the answer given by "erickson" stackoverflow.com/questions/512877/…
    • m0skit0
      m0skit0 over 10 years
      This will be available in Java 8 btw.
    • Vadorequest
      Vadorequest over 10 years
      @m0skit0 Do you have any link about that? Sounds cool.
    • m0skit0
      m0skit0 over 10 years
      @Vadorequest GIYF but anyway, check here
    • Vadorequest
      Vadorequest over 10 years
      Yeah of course I could have find it ;) But when you said something like this it's always better to give the link! Thanks.
    • LoganMzz
      LoganMzz about 9 years
      Links from official documentation : Java SE tutorial & Java Language Specification 9.2
  • Mnementh
    Mnementh over 15 years
    This explanation doesn't explain the problem. Every interface have it's own class-file, it could contain the static-method. So no lookup for a particular implementation would be needed.
  • Vlad Gudim
    Vlad Gudim over 15 years
    Not every interface type in Java is within it's own file, nor should it be according to JLS. Additionally JLS doesn't stipulate that classes have to be always stored withing a file system, quite the contrary.
  • Mnementh
    Mnementh over 13 years
    @Totophil: Interfaces must not be in a single java-file, but it will have an own class-file after compiling. That's what I wrote.
  • Mnementh
    Mnementh over 13 years
    Any reason for the downvote? A explaining comment would be nice.
  • nawfal
    nawfal over 11 years
    i am not the downvoter, but isn't this valid for non-static methods too?
  • Mnementh
    Mnementh over 11 years
    OK, here are two different possibilities. A method could be implemented or only declared. I understood, that the static method has to be implemented. In that meaning I encounter the problem presented in my answer. If you don't do that, you run into the problem Espo described - and that I didn't understand because I assumed the static method would be implemented. You also cannot declare a static abstract method for this reason, try it out, the compiler will complain.
  • nawfal
    nawfal over 11 years
    Ok, forget the implementation part. the question is why cant we declare. yes the compiler will complain and why is that is the question. to which I dont think you have answered.
  • supercat
    supercat over 11 years
    How would the situation there be any worse than having interface A contain int x(int z); and interface B contain string x(int x);? What is the meaning of x(3) in interface C?
  • Stefan
    Stefan over 11 years
    I am not sure i agree with the exact wording, but the answer does make sense in explaining why static methods in Interface should not be allowed.
  • peterk
    peterk about 11 years
    Yes - it's idealogical not technical. The reason I would like it is. that one can have a static "implementation" method in an interface that only references other "interface" methods in the interface that can be easily re-used by implementing classes. But one can declare a static class in an interface so one could have such things reside there like MyInterface.Impl.doIt(MyInterface i, Object[] args) { ... }
  • Partly Cloudy
    Partly Cloudy almost 11 years
    But static fields are allowed. I could define an A.x and a B.x on your interfaces. And in that case trying to refer to (an ambiguous) C.x causes a compile-time error. Couldn't the same thing be done for static methods? (Is that the plan in Java 8?)
  • Cruncher
    Cruncher almost 11 years
    In some reflective contexts is almost seems to make sense though
  • Cruncher
    Cruncher almost 11 years
    Just because static methods make no sense in THIS example, does not mean that they don't make sense in ANY example. In your example if the IPayable interface had static method "IncrementPayables" that kept track of how many payables were added, this would be a real use case. Of course, one could always use an abstract class, but that's not what you addressed. Your example in itself does not undermine static methods in interfaces.
  • Olivier Grégoire
    Olivier Grégoire about 10 years
    Since Java 8, you can define static methods in an interface. The methods must be public.
  • William F. Jameson
    William F. Jameson almost 10 years
    @OlivierGrégoire ...and they are not inherited, which is key.
  • Timo
    Timo about 9 years
    Good answer, though "approximately equivalent" ROFLMAO xD I would have put it more like "somewhat resembles".
  • Akki
    Akki over 8 years
    static methods are always inherited but they can't be overridden.
  • CubeJockey
    CubeJockey about 8 years
    This is not an answer to the question, at best it should be a comment.
  • Lucky
    Lucky almost 8 years
    How does this answer the question? The OP asked about interface while you wrote about class.
  • Mohamed Anees A
    Mohamed Anees A over 5 years
    OMG! We have a serious programmer(and me,commenter) answering(and me,commenting) 10 year old question.
  • Ishara
    Ishara over 5 years
    I didn't notice the date :)
  • Mohamed Anees A
    Mohamed Anees A over 5 years
    Haha! No problem!