Are static methods in Java always resolved at compile time?
short answer: yes
I wasn't able to find the exact section of the Java Language Specification. Please help. :)
Yes, but if the static method has been removed by runtime the matching method in the base class will be called (name and signature must exactly match the original method from compile time, and the method must be accessible by JVM spec rules).
To clarify, consider calling code:
Derived.fn();
And the following called code:
class Base {
public static void fn() {
System.err.println("Base");
}
}
class Derived extends Base {
public static void fn() {
System.err.println("Derived");
}
}
Prints Derived
.
Now, I compile everything. Then recompile just Derived changed to:
class Derived extends Base {
}
Prints Base
.
Perhaps then I recompile just Derived changed to:
class Derived {
}
Throws an error.
Yes, it is thoroughly investigated and explained in this thread on Sun's forums: New To Java - No late binding for static methods
Several quotes:
When the compiler compiles that class it decides at compile time which exact method is called for each static method call (that's the big difference to non-static method calls: the exact method to be called is only decided at runtime in those cases).
Calling static methods only ever depends on the compile-time type on which it is called.