tags:

views:

2497

answers:

11

There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?

Static inner types perhaps aren't a fair comparison, since that's just syntactic sugar that generates a new class, but why fields but not methods?

An argument against static methods within interfaces is that it breaks the virtual table resolution strategy used by the JVM, but shouldn't that apply equally to static fields, i.e. the compiler can just inline it?

COnsistency is what I desire, and Java should have either supported no statics of any form within an interface, or it should be consistent and allow them.

A: 

Two main reasons spring to mind:

  1. Static methods in Java cannot be overridden by subclasses, and this is a much bigger deal for methods than static fields. In practice, I've never even wanted to override a field in a subclass, but I override methods all the time. So having static methods prevents a class implementing the interface from supplying its own implementation of that method, which largely defeats the purpose of using an interface.

  2. Interfaces aren't supposed to have code; that's what abstract classes are for. The whole point of an interface is to let you talk about possibly-unrelated objects which happen to all have a certain set of methods. Actually providing an implementation of those methods is outside the bounds of what interfaces are intended to be.

Eli Courtwright
1. Classes can have static methods, and you can't override those, either. They're not there for over-riding, they're essentially just scoped functions.
skaffman
2. I agree that interfaces should npt have code, but they already do - static fields initialisers can have have code and logic of their own. So the dam has already burst, I just want consistency.
skaffman
What do you mean when you say static field initializers can have code and logic of their own? You mean that they can call a method that can be fully resolved statically to initialize themselves? This isn't code. And static init blocks aren't allowed in interface.
cynicalman
+1  A: 

Only static final fields may be declared in an interface (much like methods, which are public even if you don't include the "public" keyword, static fields are "final" with or without the keyword).

These are only values, and will be copied literally wherever they are used at compile time, so you never actually "call" static fields at runtime. Having a static method would not have the same semantics, since it would involve calling an interface without an implementation, which Java does not allow.

cynicalman
A static method is effectively "final" also, since it cannot be overriden. Hotspot copies static methods of classes all the time.
skaffman
The difference here is that there is no way to copy a function pointer around in pure Java, so if you have a call to MyInterface.STATIC_FINAL_STTRING in your code, it will literally be replaced by the value. Code would still need to be executed through an interface with no implementation.
cynicalman
+7  A: 

There is never a point to declaring a static method in an interface. They cannot be executed by the normal call MyInterface.staticMethod(). If you call them by specifying the implementing class MyImplementor.staticMethod() then you must know the actual class, so it is irrelevant whether the interface contains it or not.

More importantly, static methods are never overridden, and if you try to do:

MyInterface var = new MyImplementingClass();
var.staticMethod();

the rules for static say that the method defined in the declared type of var must be executed. Since this is an interface, this is impossible.

You can of course always remove the static keyword from the method. Everything will work fine. You may have to suppress some warnings if it is called from an instance method.

To answer some of the comments below, the reason you can't execute "result=MyInterface.staticMethod()" is that it would have to execute the version of the method defined in MyInterface. But there can't be a version defined in MyInterface, because it's an interface. It doesn't have code by definition.

DJClayworth
"They cannot be executed by the normal call MyInterface.staticMethod()." Why not? I thought this was the point of the question - why is this not allowed?
Dave L.
I agree, isn't this the point of the question? This answer is a tautology--"You can't do it because it doesn't work!"
erickson
Agreed, good answer, but to another question ;-)
Guillaume
Brian Duff
+3  A: 

Prior to Java 5, a common usage for static fields was:

interface HtmlConstants {
    static String OPEN = "<";
    static String SLASH_OPEN = "</";
    static String CLOSE = ">";
    static String SLASH_CLOSE = " />";
    static String HTML = "html";
    static String BODY = "body";
    ...
}

public class HtmlBuilder implements HtmlConstants { // implements ?!?
    public String buildHtml() {
       StringBuffer sb = new StringBuffer();
       sb.append(OPEN).append(HTML).append(CLOSE);
       sb.append(OPEN).append(BODY).append(CLOSE);
       ...
       sb.append(SLASH_OPEN).append(BODY).append(CLOSE);
       sb.append(SLASH_OPEN).append(HTML).append(CLOSE);
       return sb.toString();
    }
}

This meant HtmlBuilder would not have to qualify each constant, so it could use OPEN instead of HtmlConstants.OPEN

Using implements in this way is ultimately confusing.

Now with Java 5, we have the import static syntax to achieve the same effect:

private final class HtmlConstants {
    ...
    private HtmlConstants() { /* empty */ }
}

import static HtmlConstants.*;
public class HtmlBuilder { // no longer uses implements
    ...
}
toolkit
I agree, you can declare static final fields in an Interface, but you should not do it ;-)
Guillaume
Guil, I disagree. You should declare constants in an interface only if they're declared as valid return types or inputs for the contract specified in the interface. Yes, declaring an interface just for constants is undesired, but if the constants relate to the contract, then by all means do it.
MetroidFan2002
This doesn't address the OP's question about static methods.
bradheintz
+6  A: 

The purpose of interfaces is to define a contract without providing an implementation. Therefore, you can't have static methods, because they'd have to have an implementation already in the interface since you can't override static methods. As to fields, only static final fields are allowed, which are, essentially, constants (in 1.5+ you can also have enums in interfaces). The constants are there to help define the interface without magic numbers.

BTW, there's no need to explicitly specify static final modifiers for fields in interfaces, because only static final fields are allowed.

Alexander
First, static finals are *not* constants, that's an interview-failing answer. Secondly none of this answers why you can have static fields and inner classes in an interface, but not methods.
skaffman
Sure, you can modifiy the values of static final fields if you use complex types, but you still can't reassign them. Sure, you can bypass the idea that they are intended to be used as a replacement for magic numbers, but that's because of Java's syntax only.
Alexander
Please read my answer again if you think I haven't answered why static methods aren't allowed.
Alexander
I haven't mentioned static inner classes because you dismissed the already in your question.
Alexander
The question asks why static fields and inner classes are acceptable in interfaces. This doesn't answer that question.
Zach Langley
+4  A: 

I'm going to go with my pet theory with this one, which is that the lack of consistency in this case is a matter of convenience rather than design or necessity, since I've heard no convincing argument that it was either of those two.

Static fields are there (a) because they were there in JDK 1.0, and many dodgy decisions were made in JDK 1.0, and (b) static final fields in interfaces are the closest thing java had to consants at the time.

Static inner classes in interfaces were allows because that's pure syntactic sugar - the inner class isn't actually anything to do with the parent class.

So static methods aren't allowed simply because there's no compelling reason to do so; consistency isn't sufficiently compelling to change the status quo.

Of course, this could be permitted in future JLS versions without breaking anything.

skaffman
I must admit I still don't understand why you find it surprising that static methods aren't allowed in interfaces. It might be a good idea if you explained why they should be allowed in the first place. No offense, I'm simply curious, I can't see why static methods should be part of interfaces...
Alexander
Simply for consistency, not for design reasons. If you're going to allow statics of any kind in interfaces, then you should allow any statics, not just certain types.
skaffman
Let's forget the syntax for a second. I think Sun decided they needed a way to define constants (e.g., enums, flags) in interfaces and the closest thing that was there in Java at the time was <code>static final</code> fields. As discussed, it's not perfect (not really constants, no symmetry), but...
Alexander
A static method on an interface would be a great place to invoke the java.util.ServiceLoader to get a concrete instance.I view the "new" operator as a static method of the class to which it is applied. Look at its reflective counterpart, a method on Class that doesn't require an instance.
erickson
Consistency with what? static in fields could be used in two ways. A) class attributes and B) constants. Class attributes are not allowed in interfaces, for they just define a contract to follow and not an state or impl. Constanst are neither state or impl, just, well contants. Hence consistent.
OscarRyz
+1  A: 

Actually sometimes there are reasons someone can benefit from static methods. They can be used as factory methods for the classes that implement the interface. For example that's the reason we have Collection interface and the Collections class in openjdk now. So there are workarounds as always - provide another class with a private constructor which will serve as a "namespace" for the static methods.

A: 

The reason is that all methods defined in an interface are abstract whether or not you explicitly declare that modifier. An abstract static method is not an allowable combination of modifiers since static methods are not able to be overridden.

As to why interfaces allow static fields. I have a feeling that should be considered a "feature". The only possibility I can think of would be to group constants that implementations of the interface would be interested in.

I agree that consistency would have been a better approach. No static members should be allowed in an interface.

laz
You misunderstand the question. Read the other responses and comments.
skaffman
A: 

Static methods are tied to a class. In Java, an interface is not technically a class, it is a type, but not a class (hence, the keyword implements, and interfaces do not extend Object). Because interfaces are not classes, they cannot have static methods, because there is no actual class to attach to.

You may call InterfaceName.class to get the Class Object corresponding to the interface, but the Class class specifically states that it represents classes and interfaces in a Java application. However, the interface itself is not treated as a class, and hence you cannot attach a static method.

MetroidFan2002
+2  A: 

An official proposal has been made to allow static methods in interfaces in Java 7. This proposal is being made under Project Coin.

My personal opinion is that it's a great idea. There is no technical difficulty in implementation, and it's a very logical, reasonable thing to do. There are several proposals in Project Coin that I hope will never become part of the Java language, but this is one that could clean up a lot of APIs. For example, the Collections class has static methods for manipulating any List implementation; those could be included in the List interface.


Update: In the Java Posse Podcast #234, Joe D'arcy mentioned the proposal briefly, saying that it was "complex" and probably would not make it in under Project Coin.

erickson
+1  A: 

I often wonder why static methods at all? They do have their uses, but package/namespace level methods would probably cover 80 of what static methods are used for.

Vasil