Confused about single-dispatch in Java vs multiple dispatch

638 Views Asked by At

I’ve read a good post

Just still a little confused about the concept of multiple dispatch (not in Java) vs single dispatch (in Java).

Let’s use this example:

class A { 
    m(A a) {
       System.out.println(“In A: “ + a.getClass());
    }
}
class B extends A {
    m(A a) {
       System.out.println(“In B.m(A): “ + a.getClass());
    }
    m(B a) {
       System.out.println(“In B.m(B): “ + a.getClass());
    }
}

A a = new A();
A b = new B();
B c = new B();

a.m(a);   // Java will call A.m(A); double-dispatch would call A.m(A)
b.m(b);   // Java will call B.m(A); double-dispatch would call B.m(B)
b.m(c);   // Java will call B.m(B); double-dispatch would call B.m(B)

• Is it correct that multiple-dispatch looks at:

  1. the dynamic types of the object that’s calling the method (so, same as Java single-dispatch does)
  2. the dynamic types of the arguments being passed to the method (so, apparently not the same as Java’s single-dispatch)

• And so the difference between single-dispatch and multiple-dispatch is therefore #2 above, where single-dispatch uses the static types of the arguments instead of their dynamic types?

Thanks kindly for any insight

0

There are 0 best solutions below