No static methods in interfaces

10th February 2002

I was pretty unhappy when I first realised that Java doesn't allow static methods in interfaces, only in classes. (Jikes rejects interface Global { public static int errcode(); } saying ``static is not a valid signature modifier'').

But I have to admit that I was in the wrong on this issue. The reason for this prohibition is a fundamental one: Java resolves static method calls at compile-time (based on the type of the reference through which they're called), rather than at run time (based on the type of referenced object).

To clarify, consider this code:

	class A {
	    public static void foo() { System.out.println("A"); }
	}
	class B extends A {
	    public static void foo() { System.out.println("B"); }
	}
	public class StaticTest {
	    public static void main(String[] args) {
		A ref = new B();
		ref.foo();
	    }
	}
  

It prints ``A'', the type of the reference through which foo() was invoked, even though the object that ref refererences is actually a B.

This is very fundamental stuff and there is absolutely nothing we can do about it. What could it mean to invoke an static method on an object whose reference is of interface type?

By the way, the same issues explain why you can't have static abstract methods (Jikes says ``An abstract method may not also contain the keyword "static"'', which it a bit of a roundabout way of saying it, but unambiguous enough.)

(Of course, I could argue that Java's invocation of class methods (as opposed to object methods) is just fundamentally broken; that the former should be resolved dynamically at run-time just like the latter. But that's a much bigger battle, and not one that I could ever hope to win.)

Feedback to <mike@indexdata.com> is welcome!