Search code examples
javalate-bindingdynamic-dispatchearly-bindingstatic-dispatch

What is the difference between Binding and Dispatching in Java?


There are too many associated names: Early and Late Binding, Static and Dynamic Dispatch, Runtime vs. Compile-time Polymorphism, etc. that I don't understand the difference.

I found a clear explanation, but is it correct? I'll paraphrase JustinC:

Binding: is determining the type of a variable (object?). If it's done at compile time, its early binding. If it's done at run time, it's late binding.

Dispatch: is determining which method matches the method call. Static Dispatch is computing methods at compile time, whereas dynamic dispatch is doing it at run time.

Is Binding matching up primitive and reference variables with primitive values and objects respectively?

Edit: Please give me some clear reference material so I can read more about this.


Solution

  • I believe the confusion typically comes from how overloaded these terms are.

    We program our programs in a high level language, and either a compiler or an interpreter must transform that into something a machine actually understands.

    In coarse terms, you can picture a compiler transforming our method code into some form of machine code. If the compiler knew at that point exactly where in the memory that method would reside when we run our program later, then it could safely go and find every method invocation of this compiled method and replace it with a jump to this address where the compiled code resides, right?.

    Well, materializing this relationship is what I understand as binding. This binding, though, could happen at different moments, for example at compile time, linking time, load time, or at run time depending on the design of the language.

    The terms static and dynamic are generally used to refer to things bound before run time and at run time, respectively.

    Later binding times are associated with greater flexibility, earlier binding times are associated with greater efficiency. Language designers have to balance these two aspects when they're creating a language.

    Most object-oriented programming languages support subtype polymorphism. In these languages, virtual methods are bound at runtime depending on the dynamic type of the object at that point. In other words, virtual method invocations are dispatched to the appropriate implementation at runtime based on the dynamic type of the object implementation involved and not based solely on its static type reference.

    So, in my opinion, you must first bind the method invocation to a specific implementation or execution address, and then you can dispatch an invocation to it.

    I had answered a very similar question in the past in which I demonstrate with examples how this happens in Java.

    I would also recommend reading the book Programming Language Pragmatics. It is a great reference to learn all this kind of stuff from a theoretical standpoint.