Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving static method at compile-time

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.

like image 912
kabbi Avatar asked Jun 15 '26 06:06

kabbi


2 Answers

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.

like image 138
Chris Jester-Young Avatar answered Jun 17 '26 18:06

Chris Jester-Young


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
}
like image 37
Hot Licks Avatar answered Jun 17 '26 19:06

Hot Licks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!