Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java events vs C# - new to Java

Tags:

java

events

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.

like image 516
Without Me It Just Aweso Avatar asked Dec 06 '25 12:12

Without Me It Just Aweso


2 Answers

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?

like image 181
Pedro Avatar answered Dec 08 '25 02:12

Pedro


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

like image 22
Fedearne Avatar answered Dec 08 '25 02:12

Fedearne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!