EDIT: As of Java 8, static methods are now allowed in interfaces.
Here\'s the example:
public interface IXMLizable
Interfaces just provide a list of things a class will provide, not an actual implementation of those things, which is what your static item is.
If you want statics, use an abstract class and inherit it, otherwise, remove the static.
Hope that helps!
Something that could be implemented is static interface (instead of static method in an interface). All classes implementing a given static interface should implement the corresponding static methods. You could get static interface SI from any Class clazz using
SI si = clazz.getStatic(SI.class); // null if clazz doesn't implement SI
// alternatively if the class is known at compile time
SI si = Someclass.static.SI; // either compiler errror or not null
then you can call si.method(params)
.
This would be useful (for factory design pattern for example) because you can get (or check the implementation of) SI static methods implementation from a compile time unknown class !
A dynamic dispatch is necessary and you can override the static methods (if not final) of a class by extending it (when called through the static interface).
Obviously, these methods can only access static variables of their class.
To solve this : error: missing method body, or declare abstract static void main(String[] args);
interface I
{
int x=20;
void getValue();
static void main(String[] args){};//Put curly braces
}
class InterDemo implements I
{
public void getValue()
{
System.out.println(x);
}
public static void main(String[] args)
{
InterDemo i=new InterDemo();
i.getValue();
}
}
output : 20
Now we can use static method in interface
Interfaces are concerned with polymorphism which is inherently tied to object instances, not classes. Therefore static doesn't make sense in the context of an interface.
Well, without generics, static interfaces are useless because all static method calls are resolved at compile time. So, there's no real use for them.
With generics, they have use -- with or without a default implementation. Obviously there would need to be overriding and so on. However, my guess is that such usage wasn't very OO (as the other answers point out obtusely) and hence wasn't considered worth the effort they'd require to implement usefully.
You can't define static methods in an interface because static methods belongs to a class not to an instance of class, and interfaces are not Classes. Read more here.
However, If you want you can do this:
public class A {
public static void methodX() {
}
}
public class B extends A {
public static void methodX() {
}
}
In this case what you have is two classes with 2 distinct static methods called methodX().