title: Java Inheritance/OOP - call child type specific method with only a handle on parent
body: <p>I'm writing a game engine in Java for Android games and my engine handles collision detection for different shapes. Each shape is its own class (Square, Circle, etc.), and derives from a common abstract parent Collidable. I have a physics manager class which basically checks if any of the existing objects in the game are colliding with another, and then does the appropriate action when collision is detected. The check for collision is implemented inside each physics shape child class as in the code below.</p>
  
  <pre><code>public abstract class Collidable
  {
  }
  
  public class Square extends Collidable
  {
      public boolean Collides(Square) {...}
      public boolean Collides(Circle) {...}
      public boolean Collides(Triangle) {...}
  }
  
  public class Circle extends Collidable
  {
      public boolean Collides(Square) {...}
      public boolean Collides(Circle) {...}
      public boolean Collides(Triangle) {...}
  }
  
  public class Triangle extends Collidable
  {
      public boolean Collides(Square) {...}
      public boolean Collides(Circle) {...}
      public boolean Collides(Triangle) {...}
  }
  
  public class PhysicsMgr
  {
      public boolean Collides(Collidable p1, Collidable p2)
      {
          return p1.Collides(p2);
          // This obviously won't work because there is no Collides
          // method in Collidable. I want it to somehow call the child's
          // method and pass in p2 as its child type rather than as
          // a parent. Or somehow do this:
          return (p1.child()).Collides(p2.child());
              // I know that obviously nothing like this exists.
      }
  }
  </code></pre>
  
  <p>I am aware of "instanceof" and really don't want to check the child type of p1 and p2 versus every single collision shape I have. There must be a better way. I'm looking for either a workaround for my current problem, or preferably a redesign of my current collision detection system to avoid this problem altogether.</p>
  
  <p>Thanks!</p>