3

Possible Duplicate:
Why can’t I declare static methods in an interface?

Inside the interface body we aren't able to declare or define any static method. What is the reason? Can any one answer for this question?

Community
  • 1
  • 1
Vinoth Kumar
  • 2,953
  • 7
  • 21
  • 13
  • You should provide which language you're talking about. – mikek3332002 Aug 25 '10 at 04:20
  • http://stackoverflow.com/questions/21817/why-cant-i-declare-static-methods-in-an-interface http://stackoverflow.com/questions/512877/why-cant-i-define-a-static-method-in-a-java-interface http://stackoverflow.com/questions/129267/why-no-static-methods-in-interfaces-but-static-fields-and-inner-classes-ok – Rob Hruska Aug 25 '10 at 04:25
  • I added the Java tag since his only other question is explicitly about Java interfaces. – Chuck Aug 25 '10 at 04:25
  • If C# this is a dupe: http://stackoverflow.com/questions/259026/why-doesnt-c-allow-static-methods-to-implement-an-interface – Ian Mercer Aug 25 '10 at 04:26

1 Answers1

2

I'll assume you're talking about Java since it's by far the most popular language that has interface types. It's probably because the designers of Java figured that interfaces are contracts and implementation doesn't belong in them. The general style of Java seems to favor strictness, i.e. disallowing things unless there's a very good reason to allow them instead of the other way around.

Static methods are really just free (C-style) functions anyhow, only more annoyingly verbose. The only reason why it matters what class you put them in is aesthetics/code organization. Therefore, not allowing them to be put in interfaces isn't a severe limitation.

dsimcha
  • 64,236
  • 45
  • 196
  • 319
  • 1
    +1 - very much along the lines of what I was going to say, only better. :) If you want a static method in a hierarchy of classes then try using an abstract base class rather than an interface (if this works?). – Will A Aug 25 '10 at 04:26
  • 1
    @Will: yes, this will work. I think it's an ugly design, but that's just subjective. You should keep one thing in mind, though, if you're adding static methods at different points in a class hierarchy: you can't override a static method, you can only shadow it. What this means: if X is the parent class of Y, and both of them have a public static method f(), then it can be hard to tell in some situations which version of f() you're actually calling. – Mike Baranczak Aug 25 '10 at 05:10