Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is dispatching in JAVA?

Tags:

I am confused on what exactly dispatching is. Especially when it comes to double dispatching. Is there a simple way that I can grasp this concept?

like image 207
thunderousNinja Avatar asked Apr 01 '11 01:04

thunderousNinja


People also ask

What is dispatching in programming?

In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented programming (OOP) languages and systems.

What is dispatch method?

Dispatch Methods are the load balancing algorithms that determine how client requests are distributed between servers in a farm. AppDirector receives requests for service from clients and decides to which server to direct each request.

What is Virtual Dispatch in Java?

Java also has virtual method dispatch. A subclass can override a method declared in a superclass. So at run-time, the JVM has to dispatch the method call to the version of the method that is appropriate to the run-time type of this .

Is Java single dispatch?

Almost all well-known object oriented languages (Java, C#, JavaScript, Python, Ruby, ...) have single dispatch: Methods are chosen depending on the (single) receiver of a message. On the other hand, there is multiple dispatch which is an interesting mix of functional method selection with mutable state.


1 Answers

Dispatch is the way a language links calls to function/method definitions.

In java, a class may have multiple methods with the same name but different parameter types, and the language specifies that method calls are dispatched to the method with the right number of parameters that has the most specific types that the actual parameters could match. That's static dispatch.

For example,

void foo(String s) { ... } void foo(Object o) { ... } { foo("");           }  // statically dispatched to foo(String) { foo(new Object()); }  // statically dispatched to foo(Object) { foo((Object) "");  }  // statically dispatched to foo(Object) 

Java also has virtual method dispatch. A subclass can override a method declared in a superclass. So at run-time, the JVM has to dispatch the method call to the version of the method that is appropriate to the run-time type of this.

For example,

class Base { void foo() { ... } } class Derived extends Base { @Override void foo() { ... } }   { new Derived().foo(); }  // Dynamically dispatched to Derived.foo. {   Base x = new Base();   x.foo();                // Dynamically dispatched to Base.foo.   x = new Derived();      // x's static type is still Base.   x.foo();                // Dynamically dispatched to Derived.foo. } 

Double-dispatch is the combination of static and run-time(also called dynamic) dispatches.

like image 189
Mike Samuel Avatar answered Nov 10 '22 00:11

Mike Samuel