The actual method implementation to be called is chosen at runtime based solely on the actual type of ship. So, only the type of a single object is used to select the method, hence the name single dispatch.
Note: Single dispatch is one form of dynamic dispatch, i.e. the method is chosen at runtime. If the method is chosen at compile time (true 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 datatypes 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 we get ExplodingAsteroid hit a SpaceShip.
To support double dispatch, import the dispatch-language and include dispatch-modifiers in ExplodingAsteroid:
123456789
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.