title: How can I remove this cyclic class dependency?
body: <p>I have an <code>Entity</code> interface, implementations of which can collide with each other.  I would like to add a <code>CollisionListener</code> that is invoked when the collision takes place, which will accept a <code>CollisionEvent</code> containing the two colliding entities.  Is there a way I can do this without a cyclic dependency between <code>Entity</code> and <code>CollisionListener</code>?</p>
  
  <p>What I have currently:</p>
  
  <pre><code>public interface Entity {
  
      void addCollisionListener(CollisionListener listener);
  
      void getStrength();
  
      void dealDamage();
  
      void die();
  
      // Other methods
  }
  
  // To be implemented and added to Entities when you want to watch for collisions
  public interface CollisionListener {
      void onCollision(CollisionEvent event);
  }
  
  public class CollisionEvent {
      private final Entity source, collider;
  
      public CollisionEvent(Entity source, Entity collider) {
          this.source = source;
          this.collider = collider;
      }
  
      public Entity getSource() { return source; }
  
      public Entity getCollider() { return collider; }
  }
  </code></pre>
  
  <p>This has the following cyclical dependency:</p>
  
  <p><code>Entity -&gt; CollisionListener -&gt; CollisionEvent -&gt; Entity</code></p>
  
  <p>I'm not sure how to resolve this issue (or if it even can be resolved) because implementations of the <code>CollisionListener</code> interface should have access to the <code>Entity</code> objects affected by the collision so that it can act on them (for example, calling the <code>dealDamage</code> or <code>die</code> methods.</p>
  
  <p>I know that there's nothing strictly <em>wrong</em> with a cyclic dependency (i.e. the code compiles and runs fine), but I'd rather avoid them if at all possible.</p>