kabbi
kabbi

Reputation: 55

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.

Upvotes: 3

Views: 771

Answers (2)

Hot Licks
Hot Licks

Reputation: 47699

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
}

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223003

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.

Upvotes: 4

Related Questions