    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: An Implementation of Double Dispatch in Java</title>
        <link>https://members.accu.org/index.php/articles/496</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Design of applications and programs + Overload Journal #36 - Mar 2000</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c67/">Design</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c168/">36</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-67-168/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+67+168/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;An Implementation of Double Dispatch in Java</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 March 2000 17:50:56 +01:00 or Sun, 26 March 2000 17:50:56 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>Dynamic binding in an object oriented language means that method
calls are bound at run-time. Therefore an object's dynamic type can
be different from the static type at compilation time. In C++ each
object has a virtual table also known as the vtable. This table
contains pointers virtual methods. Java has a similar method table
since all non-static methods within the Java language are virtual
methods, by definition. Whenever a virtual method is invoked this
vtable determines the method actually called at run-time.</p>
<p>For languages like C++ and Java only the class type of the
receiving object determines the virtual table and thus the method
that is invoked in the class virtual table. We say that Java and
C++ are single dispatch languages. Sometimes there are certain sets
of applications where it would greatly help if the actual virtual
method selected is determined by looking at the types of two or
even more classes. C++ and Java do not directly support this idea
of multiple dispatch. There would be all sorts of permutations and
difficulties for implementers if the Java and C++ language were to
support multiple dispatching directly. Not to mention making sure
that any new features are all backward compatible. (This is not to
say that such an implementation is impossible.) There is one set of
applications where object design would be simplified to a large
degree if we could apply multiple dispatch techniques in both our
favourite languages.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e26" id="d0e26"></a>Arcade
Interaction</h2>
</div>
<p>Most of you may be familiar with the concept of arcade video
games. The games that you see out there in the real world, inside a
shopping mall, or just down the road, around corner at your
favourite pub, will have many moving sprite characters. You may see
the two-dimensional platform style variety or, more likely in
today's competitive games-console driven market, be entirely in
three dimensions. There will be certainly a high degree of human
user interaction, a tremendous amount of event-driven input, and
visual feed back about the state of the game's engine. The action
may be fast and furious, or it might be at slow leisurely (golfing)
pace to suit a role-playing adventurer. Whatever the style of the
game there will be definitely be interaction between various
sprites that are interacting with computer generated
characters.</p>
<p>Now let us suppose that we were writing our very own video game.
Let us also assume our moving entities (Sprites) are represented as
Java objects in a one-to-one design relationship in the video game.
Sprites in our video game will collide with each other at some
point in the game. It would be extremely useful to call a virtual
method that is dependent on the dynamic type of at least two
objects. Whenever a collision takes place between our sprites a
method call is double-dispatched. (See Figure1 WorldObject object
class UML below.)</p>
<div class="figure"><a name="d0e33" id="d0e33"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/WorldObject%20object%20class%20UML.png" align="middle"
alt="WorldObject object class UML"></div>
<p class="title c3">Figure 1. WorldObject object class UML</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>From The Bottom
Up</h2>
</div>
<p>One of the first things to do, in fact the easier task to
complete before we get started, is to write the collision detection
routines. We assume that we have a ready-made arcade <tt class=
"classname">GameEngine</tt> to hand. The engine controls the
animation loop and how the game starts and ends. More importantly
it manages the list of sprites in our game. We can add to and
remove sprites from the game engine at any time. The engine is also
responsible for displaying the sprite graphics on a window.</p>
<div class="figure"><a name="d0e47" id="d0e47"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/Sprite%20object%20class%20diagram%20simplified.png"
align="middle" alt=
"Sprite object class diagram (simplified)"></div>
<p class="title c3">Figure 2. Sprite object class diagram
(simplified)</p>
</div>
<p>Our comprehensive, but simple, game engine has a <tt class=
"classname">java.util.Vector</tt> that is container for the
<tt class="classname">WorldObject</tt>s interacting in our game.
The <tt class="methodname">checkCollision()</tt> is O(N2) loop that
checks if the rectangular boundaries of one sprite has intersected
with the bounds of another sprite. Please ignore the fact that this
is not the most efficient for-do-loop collision algorithm. If the
condition tests true then we have a collision between two sprites.
But the question is now, how do we implement <tt class=
"methodname">collide</tt>?</p>
<p>Looking at the UML class design and knowing through inspection
what the Java language provides we could run time type
identification. A Na&iuml;ve implementation of the double dispatch
would use the <tt class="literal">instanceof</tt> reserved word and
switching statement; namely the ubiquitous &quot;if / then / elseif /
then&quot; series of compound statements. It is as if we were working
backwards to come up the solution to writing a collision detection
algorithm, which we are.</p>
<div class="figure"><a name="d0e72" id="d0e72"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/Much%20more%20comprehensive%20sprite%20object%20diagram.png"
align="middle" alt=
"Much more comprehensive sprite object diagram"></div>
<p class="title c3">Figure 3. Much more comprehensive sprite object
diagram</p>
</div>
<pre class="programlisting">
public class GameEngine {
  Vector spriteList;
  ...
  public void checkCollision() {
    Enumeration etor1 = spriteList.elements();
    Enumeration etor2 = spriteList.elements();
  ...
    while ( etor1.hasMoreElements() ) {
      Sprite sprite1 = 
              Sprite)etor.nextElement();
      rect1 = sprite1.getBounds();
      while ( etor2.hasMoreElements() ) {
        Sprite sprite2 = 
              (Sprite)etor.nextElement();
        if( sprite1 == sprite2 ) continue;
        rect2 = sprite2.getBounds();
        if ( rect1.intersects(rect2) ) {
// Help? Need double dispatch in Java
// collide(sprite1,sprite2);
        }
      }
    }
  }
  ...
}

public class Player {
  public void playerAlien(WorldObject p,
                      WorldObject a ){
    if(!(p instanceof Player &amp;&amp; 
              a instanceof EnemyObject))
      return;
    Player player = (Player)p; 
    if( p instance Mantra )
                  player.playerDied();
    else if ( p instance Wriggler )
              player.increaseShields(-3);
    else if ( p instance Asteroid )
              player.increaseShields(-1);
// More code
  }
}
</pre>
<p>However, we know that a long list of switching compound
statements is flawed design practice in the long run. This was what
the concept of inheritance and virtual methods was supposed to help
us avoid, after all. When the dispatch order of magnitude equals
two, then handling the parameters is manageable. However, when the
dispatch order is greater than two orders, it takes a whole lot
more to code write a complete method that encompasses every single
collision permutation. Plus the fact is there is a going be
tremendous amount of code maintenance if we add several more
characters to our game. Also note the difficulties involved, when
the language does not support directly multiple-dispatching.
Observe how ugly the type casting gets. It certainly is not ideal.
The input parameters have to be in terms of the super class
<tt class="classname">WorldObject</tt>. Additionally, before we
could write such laborious code, even if we want to write it, we
need find out the answer to a vital question: in which class do you
place the double dispatch method? Does the <tt class=
"methodname">playerAlien()</tt> method belong in the <tt class=
"classname">Player</tt> class or one of the many <tt class=
"classname">Alien</tt> classes? Or perhaps, more than reasonably
likely, it belongs in neither class. [<i><span class=
"remark">Editoral note from Mike Woolley: That's what happens in
CLOS (the only language I'm familiar with that supports multiple
dispatch). &quot;Generic Functions&quot; don't &quot;belong&quot; to any particular
class.</span></i>]</p>
<div class="informaltable">
<table border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>1st Class Name</th>
<th>2nd Class Name</th>
<th>Dispatch Method</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Player</td>
<td>Wriggler</td>
<td>playerDies()</td>
</tr>
<tr>
<td>Wriggler</td>
<td>Player</td>
<td>playerDies()</td>
</tr>
<tr>
<td>Player</td>
<td>Mantra</td>
<td>playerDies()</td>
</tr>
<tr>
<td>Bomblet</td>
<td>Player</td>
<td>playerDies()</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>Pod</td>
<td>Laser</td>
<td>spawnHeatSeeker()</td>
</tr>
<tr>
<td>Laser</td>
<td>Mantra</td>
<td>alienDies()</td>
</tr>
<tr>
<td>Laser</td>
<td>Wriggler</td>
<td>alienDies()</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
&lt;/tbody&gt;
</table>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e173" id="d0e173"></a>Database
Approach</h2>
</div>
<p>Instead of a convoluted series of if/then/else statements, let
us use a table of method pointers, just like C++ implementations do
with internal virtual method tables. Java allows us obtain a
reference to the <tt class="classname">java.lang.Class</tt> object.
The <tt class="classname">java.lang.Class</tt> class is a template
for all Java object instances. Therefore, its <tt class=
"classname">Class</tt> object can identify the type of an object
instance. The <tt class="classname">Class</tt> class has an
instance method called <tt class="methodname">getName()</tt> that
returns a <tt class="classname">String</tt> object. This will be
the class name and, of course, it is guaranteed to be unique
(Assuming the class have been loaded through the same <tt class=
"classname">ClassLoader</tt>).<sup>[<a name="d0e199" href=
"#ftn.d0e199" id="d0e199">1</a>]</sup></p>
<p>If we take a database approach to the double-dispatching problem
it is apparent that we querying on to three columns that are
primary keys. This table provides a huge clue to how double
dispatch could be implemented! Each tuple of these data rows is
guaranteed to be unique. The tool to hand is a basic associative
array (<tt class="classname">java.util.Hashtable</tt>). We can
combine the first two columns, the colliding (<tt class=
"classname">Sprite</tt>) class names, and combine both of them as
the key into the <tt class="classname">Hashtable</tt> container. We
store the method as the value in the <tt class=
"classname">Hashtable</tt> referring to it with our doctored key.
But how do we store a method in Java? Are you thinking we should
really use the Java Reflection API to get the <tt class=
"classname">java.lang.reflect.Method</tt>? Oh no, you don't!
Although callbacks are great for C++ and C languages it can be
shown that it is always better to use a class or interface to
represent a callable method rather than a method itself, especially
in Java. In fact the power of the interface concept allows us to
declare a programming abstraction that directly conceptualizes what
we are trying to achieve.</p>
<pre class="programlisting">
public interface CollisionListener {
  public void collisionDetected( 
    WorldObject obj1, 
    WorldObject obj2 );
}
</pre>
<p>The interface <tt class="classname">CollisionInterface</tt>
contains a method that has a signature for a method that accepts
two objects that have collided, where <i class=
"parameter"><tt>obj1</tt></i> is the first object that collided and
<i class="parameter"><tt>obj2</tt></i> the second object that
collided. All we need to do then is write functor objects that
implement the <tt class="methodname">CollisionDetected</tt> public
method.</p>
<p>So instead of storing a method in our <tt class=
"classname">Hashtable</tt> we store a listener object, in the exact
same fashion as a <tt class=
"classname">java.awt.ActionListener</tt> is registered with a
<tt class="classname">java.awt.Button</tt> component. (It will be
familiar to those of you who programmed with the Java Abstract
Window Toolkit.) At registration we require the two classes to
complete a key to store our <tt class=
"classname">CollisionListener</tt> value in the <tt class=
"classname">Hashtable</tt>.</p>
<p>The next listing shows the full source to a double dispatcher
<tt class="classname">CollisionMapDispatcher</tt>. This Java class
is a singleton object although it does not necessarily have to be
one. An application can only get a reference to the dispatcher by
calling the static method <tt class="methodname">getInstance()</tt>
since the constructor for the class is private. The interesting
method is <tt class="methodname">addCollisionListener</tt> that
takes references to the two colliding classes and a <tt class=
"classname">CollisionListener</tt>. The method generates a key for
the <tt class="classname">Hashtable</tt> by using an arbitrary
separator string and puts the listener into the <tt class=
"classname">Hashtable</tt> using the key. The method called
<tt class="methodname">fireCollisionEvent()</tt> is exactly the
method <tt class="methodname">collide()</tt> that we were trying
build in the example at the beginning of this article. It takes two
object classes and builds a key with the separator string. If there
is matching key in the <tt class="classname">Hashtable</tt> then
that collision listener is called with the two-class parameter.
Notice that there is a trivial search optimisation going on here.
If there is no such value <tt class="literal">V</tt> in the
<tt class="classname">Hashtable</tt> <tt class="literal">H</tt> for
a key <tt class="literal">K(s1,s2)</tt> then try the key <tt class=
"literal">K(s2,s1)</tt>. In other words a <tt class=
"classname">Player</tt> that collides with a <tt class=
"classname">Mantra</tt> has the same outcome as a <tt class=
"classname">Mantra</tt> that collides with <tt class=
"classname">Player</tt>: instant death of the <tt class=
"classname">Player</tt>. This is fine if the order of dispatch
equals two and we don't care about of the order of the collision
parameters.</p>
<pre class="programlisting">
public final class CollisionMapDispatcher { 
  private final static String SEPARATOR=&quot;&lt;+&gt;&quot;; 
  private Hashtable map;
  
  private static CollisionMapDispatcher
 dispatcher = new CollisionMapDispatcher();

  private CollisionMapDispatcher() {
    map = new Hashtable();
  }

  public static 
  CollisionMapDispatcher getInstance(){
     return(dispatcher);
  }
  
  public void addCollisionListener( 
    Class class1, 
    Class class2, 
    CollisionListener listener){
// FIXME: should check the classes are
// WorldObject type.
    String s1 = class1.getName();
    String s2 = class2.getName();
    CollisionTuple tuple = 
      new CollisionTuple( s1, s2, listener);
    map.put( s1 + SEPARATOR + s2, tuple);
  }

  public void fireCollisionEvent(WorldObject obj1,
                    WorldObject obj2) {
    String s1 = obj1.getClass().getName();
    String s2 = obj2.getClass().getName();
    CollisionTuple tuple = 
    (CollisionTuple)map.get(
                     s1 + SEPARATOR + s2);
    if(tuple != null) {
// Call the collision listener object
    tuple.listener.collisionDetected(obj1,
                        obj2);
    }
    else {
// Reverse the order
    tuple =(CollisionTuple)map.get( 
                  s2 + SEPARATOR + s1);
    if(tuple != null) {
// Call the collision listener object
      tuple.listener.collisionDetected(obj2,
                          obj1);
    }
    else {
// throw new InternalError(&quot;cannot handle 
// collision between classes `&quot;+ s1+&quot;' and 
// `&quot;+s2+&quot;'&quot;);
      return;
    }
  }
}
// ---------------------------
// I N N E R  C L A S S E S
// ---------------------------
  private static class CollisionTuple {
     String objectClass1;
    String objectClass2;
    CollisionListener listener;

    public CollisionTuple(String class1,
                      String class2, 
             CollisionListener listener) {
      this.objectClass1 = class1;
      this.objectClass2 = class2;
      this.listener = listener;
    }
  }
}
</pre>
<p>The <tt class="classname">CollisionMapDispatcher</tt> uses a
private inner class to store a tuple (all of the columns of data to
make up one row of data in a relational database table). Now that
we have our double dispatcher we can use it directly in our video
game application.</p>
<pre class="programlisting">
public class CollisionHandler {
  public final static EmptyListener
      EMPTY_LISTENER = new EmptyListener();
  private CollisionMapDispatcher dispatcher
     = CollisionMapDispatcher.getInstance();
  public static void starshipAndAlien( 
  WorldObject player, WorldObject alien)   {
// Player crashed into a Mantra; instant death

    Player p =(WorldObject)Player;
    p.playerDied();
    p.destroy();
    alien.destroyed();
  }
  ...
  public static void registerAllCollisions(){
    dispatcher.addCollisionListener(
        Player.class, Mantra.class,
        new CollisionListener() {
          public void collisionDetected( 
                     WorldObject obj1,
                   WorldObject obj2) {
            playerAndAlien( obj1, obj2);
          }
        } );
  ...
// More collisions registered here
  }
// ---------------------------
// I N N E R  C L A S S E S
// ---------------------------
  public static class EmptyListener 
  implements CollisionListener {
    public void collisionDetected( 
       WorldObject obj1, WorldObject obj2) {
// Do nothing
    }
  }
}
</pre>
<p>The most confusing aspect of the above code is in the <tt class=
"methodname">registerAllCollision()</tt> method. We are creating
in-line Java object classes, here, so called anonymous class. The
Java compiler builds an unnamed object that implements the
<tt class="classname">CollisionListener</tt> interface and has, by
definition a public <tt class="methodname">collisionDetected()</tt>
method. This method is a wrapper that calls the handler's static
collision method. The long-winded less efficient implementation
would be functionally equivalent to the following code:</p>
<pre class="programlisting">
public class CollisionHandler {
    ...
    public static void registerAllCollisions(){
      dispatcher.addCollisionListener(
        Player.class, Mantra.class,
        new __JavaC_Anonymous_450971() );
// More collisions registered here ...
    }
// Compiler made up
    private class __JavaC_Anonymous_450971
    extends Object
    implements CollisionListener(){
      public void collisionDetected( 
       WorldObject obj1, WorldObject obj2 ){
            playerAndAlien( obj1, obj2 );
      }
    }
    ...
}
</pre></div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e333" id="d0e333"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Meyers" id="Meyers"></a>
<p class="bibliomixed">[Meyers] &quot;Item 31: Making functions virtual
with respect to more than one object&quot;, <span class=
"citetitle"><i class="citetitle">More Effective C++</i></span> by
Scott Meyers, Addison Wesley, ISBN 0-201-63371-X</p>
</div>
<div class="bibliomixed"><a name="Defender" id="Defender"></a>
<p class="bibliomixed">[Defender] &quot;Humanoid Arcade Video Game&quot;, a
clone of the popular classic Defender written purely in Java.
Licensed under Open Source. <span class="bibliomisc"><a href=
"http://www.xenonsoft.demon.co.uk/humanoid/humanoid.html" target=
"_top">www.xenonsoft.demon.co.uk/humanoid/humanoid.html</a></span></p>
</div>
<div class="bibliomixed"><a name="FAQ" id="FAQ"></a>
<p class="bibliomixed">[FAQ] &quot;The Java FAQ&quot; on-line at <span class=
"bibliomisc"><a href="http://www.afu.com/javafaq.html" target=
"_top">www.afu.com/javafaq.html</a></span> and follow the links
from there to get to Peter Van Linden's semi-official Frequently
Asked Questions web pages.</p>
</div>
</div>
<div class="glossary">
<div class="titlepage">
<h2><a name="d0e352" id="d0e352"></a>Glossary</h2>
</div>
<div class="glossdiv">
<h3></h3>
<dl>
<dt>Casting</dt>
<dd>
<p>See between one type to another type explicitly tells the
compiler to change the apparent type of a reference. The principle
is the same in C++ as it is in Java, except that Java checks the
legality of the cast at run-time as well as at compilation-time.
Attempting to cast an object to an illegal type will result in a
<tt class="classname">ClassCastException</tt> being thrown at
run-time..</p>
</dd>
<dt>Interfaces</dt>
<dd>
<p>See in a Java are declarations of groups of public methods and
constants. Interface act like class types that on first inspection
look like purely abstract classes. The difference between an
interface and an <tt class="literal">abstract</tt> class is that an
interface just declares the methods that an object class is
obligatory contracted to implement. Interfaces make better
callbacks in Java. A callback is a way to respond to a reply and
act on it much later after first passing a reference object. In C
and C++ you would practically use function pointers or pointers to
class member functions. In Java, you can use interfaces to
encapsulate this functor-like behaviour..</p>
</dd>
<dt>Inner classes</dt>
<dd>
<p>See are a powerful structural concept that has been part of Java
since version 1.1. They are nested classes that can be declared at
any level of scope. Think of those Russian doll ornaments then you
will get the idea..</p>
</dd>
<dt>Anonymous inner-classes</dt>
<dd>
<p>See are like a powerful shorthand for creating convenient
utility classes, almost in-lined (the source code is in-lined, the
byte-code lives in a separate class file), classes on the fly.
Anonymous inner classes are really Java's attempt at &quot;lexical
closures&quot; (with the additional restriction that locals that are
referenced in the enclosing scope must be &quot;final&quot;)..</p>
</dd>
</dl>
</div>
</div>
<div class="footnotes"><br>
<hr class="c4" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e199" href="#d0e199" id=
"ftn.d0e199">1</a>]</sup> (Within the namespace of a class loader -
different class loaders could conceivably have loaded classes with
the same names).</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
