Early and Late Binding in Java and Groovy

  • Posted on: 14 November 2016
  • By: rob

Take a moment to consider the following snip of Java code.
What is the output of the program? Do you expect to see "String Value = Hello World" or "Object Value = Hello World"?

public class Test {
  public static void main(String [] args) {
    String s = "Hello World";
    Object obj = s;
    new Test().method(obj);
  }
  public void method (String s) {
    System.out.println("String Value = " + s);
  }
  public void method (Object s) {
    System.out.println("Object Value = " + s);
  }
}






Well, we have a String object that has a String reference s. We then create an object reference that refers to our String. We call a method that has both String and Object signatures. In Java, the method to call is determined by the Java compiler, not the runtime environment (early or static binding) and so the output is "Object Value = Hello World". This is in contrast to languages that implement late binding where the method to use is determined at runtime and we would see "String Value = Hello World".

The surprise comes when we run the same code in Groovy. You can try this using a groovy web console. Groovy is an optionally typed and dynamic language for the Java platform. The method to invoke is determined at runtime, and we can see that the output from Groovy is "String Value = Hello World".

In summary, run this code in a Java class to get

Object Value = Hello World

and run this code in a Groovy class to get

String Value = Hello World