0

I am not sure if i have wrong idea about double dispatch. But this is what i thought:

class A{
   void testA( B obj ){
         System.out.println( "A-Parent" );
          obj.testB();
   }
}


class AChild extends A{
   void testA( B obj ){
         System.out.println( "A-Child" );
         obj.testB();
   }
}


class B{
   void testB(){
         System.out.println( "B-Parent" );
   }
}


class BChild extends B{
   void testB(){
         System.out.println( "B-Child" );
   }
}

class Launcher{
  public static void main(){
  A objA = new AChild();
  B objB = new BChild();

  objA.testA(objB);
  }
}

What I expected:

A-Child
B-Parent

Actual output:

A-Child
B-Child   // How ???????

I thought Java resolves objA to Achild correctly during run time while the parameter is resolved during compile time to B, due to Javas Single diapatch. please tell me where i got it wrong?

broun
  • 2,483
  • 5
  • 40
  • 55
  • changed, perils of writing code in notepad :) – broun Jan 25 '13 at 06:20
  • 2
    consider changing your main method also.. !!! – Vijay C Jan 25 '13 at 06:23
  • Found the issue here. I thought since the arguments are statically resolved the resulting method will use the method defined in the resolved class. but java always resolves the receiver object at runtime. http://java.dzone.com/articles/multiple-dispatch-fix-some – broun Jan 25 '13 at 07:11

2 Answers2

1

Don't see reason why 'B-Parent' should be printed instead of 'B-Child'

     B objB = new BChild();
     objA.testA(objB);

objB actually have an instance of child of B. So B-Child will get printed. So this is run time binding or Polymorphism feature of Java in action :)

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
-3

you need to use the http://en.wikipedia.org/wiki/Visitor_pattern to implement double dispatch in java.

Ray Tayek
  • 9,841
  • 8
  • 50
  • 90
  • I understand that visitor pattern is a hack to support double dispatch in java. My question is about double dispatch and the way java handles the scenario. thanks for the comment. – broun Jan 25 '13 at 06:21