Are static methods in Java always resolved at compile time?

Deadly 提交于 2019-12-29 06:52:18

问题


Are static methods in Java always resolved at compile time?


回答1:


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.




回答2:


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.




回答3:


short answer: yes

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



来源:https://stackoverflow.com/questions/1039229/are-static-methods-in-java-always-resolved-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!