title: Polymorphically Dispatching in Java
body: <p>In the following, I want EventHandler to handle EventA one way, EventB another way, and any other Events (EventC, EventD) yet another way.  EventReceiver receives only a reference to an Event and calls EventHandler.handle().  The version that always gets called, of course, is EventHandler.handle(Event event).</p>
  
  <p>Without using instanceOf, is there a way to polymorphically dispatch (perhaps via another method in EventHandler or generics) to the appropriate handle method?</p>
  
  <pre><code>class EventA extends Event {
  }
  
  class EventB extends Event {
  }
  
  class EventC extends Event {
  }
  
  class EventD extends Event {
  }
  
  class EventHandler {
      void handle(EventA event) {
         System.out.println("Handling EventA");
      }
  
      void handle(EventB event) {
         System.out.println("Handling EventB");
      }
  
      void handle(Event event) {
         System.out.println("Handling Event");
      }
  }
  
  class EventReceiver {
      private EventHandler handler;
  
      void receive(Event event) {
          handler.handle(event);
      }
  }    
  </code></pre>