Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1.  
  2. class SpaceShip {}
  3. class GiantSpaceShip extends SpaceShip {}
  4.  
  5. class Asteroid {
  6.  
  7.   public void collideWith(SpaceShip sp) {
  8.     System.out.println("Asteroid hit a SpaceShip");
  9.   }
  10.   public void collideWith(GiantSpaceShip gsp) {
  11.     System.out.println("Asteroid hit a GiantSpaceShip");
  12.   }
  13. }
  14.  
  15. class ExplodingAsteroid extends Asteroid {
  16.  
  17.   public void collideWith(SpaceShip sp) {
  18.     System.out.println("ExplodingAsteroid hit a SpaceShip");
  19.   }
  20.   public void collideWith(GiantSpaceShip gsp) {
  21.     System.out.println("ExplodingAsteroid hit a GiantSpaceShip");
  22.   }
  23. }
  24.  
  25. public class DoubleDispatchTest { public static void main(String args[]) {
  26.     Asteroid ast = new Asteroid();
  27.     Asteroid ast1 = new ExplodingAsteroid();
  28.     SpaceShip sp = new SpaceShip();
  29.     SpaceShip sp1  = new GiantSpaceShip();
  30.  ast.collideWith(sp);
  31.  ast.collideWith(sp1);
  32.  ast1.collideWith(sp);
  33.  ast1.collideWith(sp1);
  34.  }
  35. }
  36.  
  37. Output:
  38. Asteroid hit a SpaceShip
  39. Asteroid hit a SpaceShip
  40. ExplodingAsteroid hit a SpaceShip
  41. ExplodingAsteroid hit a SpaceShip
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement