views:

451

answers:

3

Are static methods in Java always resolved at compile time?

+2  A: 

short answer: yes

I wasn't able to find the exact section of the Java Language Specification. Please help. :)

dfa
please, is there any dodgy case when the rule does not apply?
Another short answer: No.
Carl Manaster
@Joao: in Java static modifier means exactly "at compile-time". The method/variable is bound statically at the class name. No exceptions.
dfa
@dfa: I'm sorry if that was unclear; my short answer was in response to @Joao Luis' followup question. Your short answer was of course correct and I didn't mean to imply otherwise.
Carl Manaster
+4  A: 

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.

Tom Hawtin - tackline
"Removed by runtime"? What does that mean?
Michael Myers
I'm guessing it means: if a class is compiled to call Sub.x(), then the x() method is deleted from Sub but the caller class is not recompiled, at runtime Base.x() will be invoked if it exists.
erickson
+1 probably this is the right approach to this question
dfa
excelent point! +1
Igor Soarez
+4  A: 

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."

Roee Adler
Correct answer for the question, but the quote about non-static methods only decided at runtime is incorrect. Only overridden methods are decided at runtime, others are determined at compile time, including overridden.
Robin
@Robin: the quote is not mine, good point though :)
Roee Adler