StaticCallPolymorphic
DRAFT

Misconception:

When calling a static method m(x), Java at runtime finds and invokes the static method m(...) with the type corresponding to the dynamic type of x.

Incorrect

A static method call is dispatched polymorphically at runtime based on the argument types

Correct

Correction
Here is what's right.

public class C {
}
public class Sub1 extends C {
}
public class Sub2 extends C {
}
public class Test {
  public void test(C c) {
    work(c); // this does NOT dynamically dispatch based on c
  }
  public static void work(C c) { /*implementation*/ }
  public static void work(Sub1 s1) { /*implementation*/ }
  public static void work(Sub2 s2) { /*implementation*/ }
}

If you want a polymorphic call in Java, you have to use instance methods.

public class C {
  public void work() { /*implementation*/ }
}
public class Sub1 extends C {
  public void work() { /*implementation*/ }
}
public class Sub2 extends C {
  public void work() { /*implementation*/ }
}
public class Test {
  public void test(C c) {
    c.work(); // this DOES dynamically dispatch based on c
  }
}

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.