title: Java Equivalent to C#'s Delegates/Events: Changing Event Invoked Code Dynamically
body: <p>I have a simple <code>Screen</code> class in C# that has a bunch of events (with corresponding delegates) like the <code>FadeOutEvent</code>.</p>
  
  <p>I want to port my library to Java, and I find that the mechanism for events/delegates is really cludgey. Specifically, I cannot easily write code like:</p>
  
  <pre><code>if (someVar == someVal) {
    this.FadeOutComplete += () =&gt; {
      this.ShowScreen(new SomeScreen());
    };
  } else {
    this.FadeOutComplete += () =&gt; {
      this.ShowScreen(new SomeOtherScreen());
    };
  }
  </code></pre>
  
  <p>For all you Java-only guys, essentially, what I'm whinging about is the inability to reassign the event-handling method in the current class to something else dynamically, <strong>without creating new classes</strong>; it seems that if I use interfaces, the current class <strong>must</strong> implement the interface, and I can't change the code called later.</p>
  
  <p>In C#, it's common that you have code that:</p>
  
  <ul>
  <li>In a constructor / early on, assign some event handler code to an event</li>
  <li>Later during execution, remove that code completely</li>
  <li>Often, change that original handler to different handler code</li>
  </ul>
  
  <p>Strategy pattern <em>can</em> solve this (and does), albeit that I need extra classes and interfaces to do it; in C#, it's just a delcarative event/delegate and I'm done.</p>
  
  <p>Is there a way to do this without inner/anonymous classes?</p>
  
  <p><strong>Edit:</strong> I just saw <a href="https://stackoverflow.com/questions/1073358/function-pointers-in-java">this SO question</a>, which might help.</p>