It's a common fact that Java compiler (almost) always resolves static methods at compile time. For example:
public class Super {
static void someMethod() {
// Do something...
}
}
public class Derived extends Super {
// Some other methods, excluding someMethod
}
Test code:
Derived derived = new Derived();
derived.someMethod();
This should call Super.someMethod(), right? And it should be resolved at compile-time, so that javac would generate invokestatic Super.someMethod, but I've seen that it generates invokestatic Derived.someMethod. Why is it doing so? And is there a way to somehow change this behavior?
Please correct me, if I am wrong.
Let's assume that there's an intermediate superclass between Super and Derived (called, say, Intermediate).
The reason the compiler generates Derived.someMethod is that you might recompile Intermediate to insert an implementation of someMethod, which would shadow the implementation from Super.
For the record:
public class TestSuperDerived {
public static void main(String[] argv) {
DerivedClass.someMethod();
}
}
class SuperClass {
static void someMethod() {
System.out.println("Here!");
}
}
class DerivedClass extends SuperClass {
// Some other methods, excluding someMethod
}
javap output:
C:\JavaTools>javap -c TestSuperDerived
Compiled from "TestSuperDerived.java"
public class TestSuperDerived {
public TestSuperDerived();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: invokestatic #2 // Method DerivedClass.someMethod:()V
3: return
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With