The actual method implementation, which the interpreter should call, is chosen at runtime based solely on the actual type of ship. The interpreter only uses the type of a single object to select the method, hence the name single dispatch.
Note: Single dispatch is one form of dynamic dispatch. For example, the interpreter chooses the method at runtime. If the compiler decides the method at compile time (valid for all non-virtual methods), it's called static dispatch.
publicclassAsteroid{publicvoidcollideWith(SpaceShips){System.out.println("Asteroid hit a SpaceShip");}publicvoidcollideWith(ApolloSpacecrafta){System.out.println("Asteroid hit an ApolloSpacecraft");}}publicclassExplodingAsteroidextendsAsteroid{publicvoidcollideWith(SpaceShips){System.out.println("ExplodingAsteroid hit a SpaceShip");}publicvoidcollideWith(ApolloSpacecrafta){System.out.println("ExplodingAsteroid hit an ApolloSpacecraft");}}publicclassDoubleDispatch{publicstaticvoidmain(string[]args){AsteroidtheAsteroid=newAsteroid();SpaceShiptheSpaceShip=newSpaceShip();ApolloSpacecrafttheApolloSpacecraft=newApolloSpacecraft();theAsteroid.collideWith(theSpaceShip);// output: (1) theAsteroid.collideWith(theApolloSpacecraft);// output: (2)System.out.println();ExplodingAsteroidtheExplodingAsteroid=newExplodingAsteroid();theExplodingAsteroid.collideWith(theSpaceShip);// output: (3)theExplodingAsteroid.collideWith(theApolloSpacecraft);// output: (4)System.out.println();AsteroidtheAsteroidReference=theExplodingAsteroid;theAsteroidReference.collideWith(theSpaceShip);// output: (5)theAsteroidReference.collideWith(theApolloSpacecraft);// output: (6)System.out.println();// Note the different data types SpaceShiptheSpaceShipReference=theApolloSpacecraft;theAsteroid.collideWith(theSpaceShipReference);// output: (7)theAsteroidReference.collideWith(theSpaceShipReference);// output: (8)}}
Asteroid hit a SpaceShip
Asteroid hit an ApolloSpacecraft
Exploding Asteroid hit a SpaceShip
Exploding Asteroid hit anApolloSpacecraft
Exploding Asteroid hit a SpaceShip
Exploding Asteroid hit an ApolloSpacecraft
Asteroid hit an ApolloSpacecraft
ExplodingAsteroid hit a SpaceShip
The desired result here would be ExplodingAsteroid hit an ApolloSpacecraft, but instead, you get ExplodingAsteroid hit a SpaceShip.
To support double dispatch, import the dispatch language and include dispatch modifiers in ExplodingAsteroid:
publicclassExplodingAsteroidextendsAsteroid{publicdispatchvoidcollideWith(SpaceShips){System.out.println("ExplodingAsteroid hit a SpaceShip");}publicdispatchvoidcollideWith(ApolloSpacecrafta){System.out.println("ExplodingAsteroid hit an ApolloSpacecrat");}}
The last method now correctly returns ExplodingAsteroid hit an ApolloSpacecraft.