Why does Java enforce return type compatibility for overridden static methods?

Consider the following:

public class Foo {
  static class A {
    public static void doThing() {
      System.out.println("the thing");
    }
  }

  static class B extends A {

  }

  static class C extends B {
    public static void doThing() {
      System.out.println("other thing");
    }
  }

  public static void main(String[] args) {
    A.doThing();
    B.doThing();
    C.doThing();
  }
}

Run it! It compiles and prints out

the thing
the thing
other thing

Static methods sort of inherit — in the sense that B.doThing is translated into a call to A.doThing — and can sort of be overridden.

This seems like it was mostly a judgement call for the JLS. The most specific way the JLS seems to address this, though, is section 8.2, which simply doesn’t say that static methods aren’t inherited.

Leave a Comment