0

I have an abstract class with a few inheriting classes that represent shapes and I would like to test for collisions. For now, here is my (Java) code:

public abstract class Shape {
  public abstract boolean collision(Rectangle rectangle);
  public abstract boolean collision(Circle circle);
}

public class Rectangle extends Shape {
  // implementation of both abstract methods
}

public class Circle extends Shape {
  // implementation of both abstract methods
}

I see the flaw in my code: I have to modify every class if I want to add another child class, say Triangle. Not to mention that the parent class must know all its children (as pointed out @deceze).

I still would like to be certain that every collision is possible (Rectangle-Rectangle, Circle-Circle, Rectangle-Circle and Circle-Rectangle, plus the 5 more that Triangle would introduce, and so on).

Is there a design pattern that I haven't thought of that solves that problem nicely?

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • It would appear that if you discovered a *general, arbitrary shape collision algorithm*, your problem would solve itself. As for class design, most certainly the parent class should not define methods specific to child classes. Parents can't know about all possible children of theirs; anyone could `extend Shape` at any time without it knowing about it. – deceze Mar 30 '16 at 07:59
  • @deceze Glad we agree on this one. Also: LOL. – SteeveDroz Mar 30 '16 at 08:01
  • Look into double dispatch and the Visitor pattern http://stackoverflow.com/questions/6762256/how-does-double-dispatch-work-in-visitor-pattern – Raedwald Mar 30 '16 at 08:41

0 Answers0