tags:

views:

71

answers:

3

I am new to the world of Java. I'm coming from C#. I'm trying to set up a custom event. Here is how I would have done this in C#

class A
{
   public EventHandler Changed;

   public void FunctionA() 
   {
       if(Change != null)
            Changed(this, null); //fire the event!
   }
}

class B
{
     private A instanceOfA = new A();
     public void FunctionB()
     {
        A.Changed+= new EventHandler(onAChanged); //subscribe to event
     }
     public void onAChanged(object sender, EventArgs args)
     {
          //handle the event
     }
 }

Now I've been trying to read about java custom events but all the samples I find show me having to make 2 custom classes ( http://www.exampledepot.com/egs/java.util/custevent.html ) Am I missing something? it seems like there has to be an easier way to do events than the guide above.

+3  A: 

There is no event in the Java language. You have to use a pattern like the one you provided for event handling.

Fedearne
A: 

In Java there is no concept of a delegate and therefore no C# style "events". To achieve a similar system, you need to use the Observer pattern as demonstrated in the link you provided.

Steve_
+2  A: 

Like said, in java events are a pattern, in C# they are a language feature. The link you provided is the correct way of dealing with events.

"Amazing", no?

Pedro