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 Answers 3

4

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.