7

I've been looking through a lot of OOP Design Patterns lately, and I've run into some strange things I've never seen before:

Button button =  new Button(shell, SWT.PUSH);
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
    // Handle the selection event
    System.out.println("Called!");
    }
}); 

Specfically, what does this do (eg. what does the "new" keyword do here)?:

    button.addSelectionListener(new SelectionAdapter() {

Second question:

private void notifyListeners(Object object, String property, String oldValue, String newValue) {
   for (PropertyChangeListener name : listener) {
      name.propertyChange(new PropertyChangeEvent(this, "firstName", oldValue, newValue));
   }
}

This is a snippet from an observer design pattern. To my new understanding, the name.propertyChange(...) creates an object of PropertyChangeEvent and through Java's observer pattern implementation, automatically notifies the observers by sending this new object's information to the observers (or something very similar to this). Is this correct?

Asad
  • 1,817
  • 16
  • 23
Shaku
  • 670
  • 1
  • 8
  • 19
  • Note that in this particular case (interface with single "Selected" method) C# equivalent code usually written using "event" - [Handling and Raising Events](http://msdn.microsoft.com/en-us/library/edzehd2t.aspx) instead of interface with single member. – Alexei Levenkov Aug 01 '13 at 02:01
  • It is an abstract class which means you can create a new anonymous class that implements it. Handy for short tasks. – arynaq Aug 01 '13 at 02:01
  • 6
    Try not to ask multiple unrelated questions in the same post. Ask a new question instead. – Paul Bellora Aug 01 '13 at 02:02
  • I've answered your second question. – William Morrison Aug 01 '13 at 02:12
  • possible duplicate of [How are Anonymous (inner) classes used in Java?](http://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java) – Dariusz Aug 01 '13 at 06:22

3 Answers3

23

Here, the new keyword is creating an anonymous class.

This is useful when you need a listener to perform some action, and you'd like to keep your code grouped together, and/or the class is "one-off", meaning it has no use elsewhere.

Here's a link to sun's tutorial on anonymous classes. All the normal rules of classes apply. You need to implement abstract methods, or all methods when creating an interface.

Scope is a little different as you can access variables declared in the class your anonymous class is nested within. However, you can't access local variables from an anonymous class unless those local variables are declared final. For instance:

Button button =  new Button(shell, SWT.PUSH);
final String someString = "hello world!";
button.addSelectionListener(new SelectionAdapter() { 
    @Override
    public void widgetSelected(SelectionEvent e) {
        // Handle the selection event
        System.out.println(someString);
    }
});

If someString were declared in more global scope, this would not be the case.

To your second question:

Yes. You are correct, that's what's happening in the snippet. Notice a new PropertyChangeEvent is being created every time? This is so listeners appearing earlier in the list don't modify the PropertyChangeEvent for items appearing later in the list.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
4

First of all, this is a Java-specific syntax: there is no comparable syntax in C#, where you must either create an anonymous class extending object, or create an instance of a named class.

In Java this syntax lets you create an anonymous subclass of SelectionAdapter, overriding any methods as you see fit. This is equivalent to creating a named class that extends SelectionAdapter, overriding any methods as you do in the curly braces following the SelectionAdapter() constructor call, and then using the name of that derived class in the call of addSelectionListener. The only difference is that such derived class would have a name, while the anonymous class from your example does not have a name * available to programmers.

* Internally anonymous classes do have names: you can see them if you look at the list of class files generated by the Java compiler. Files with dollar signs and numbers in their names correspond to anonymous classes.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • So, essentially, this is just a temporary object being created at runtime when the button is pressed, and then falls out of scope soon as it's overidden methods finish executing? – Shaku Aug 01 '13 at 01:49
  • @Shaku Not only the object is temporary, but also the class structure is unique to that invocation. – Sergey Kalinichenko Aug 01 '13 at 01:50
  • C# does however, have anonymous delegates. That's the closest thing to an equivalent. – William Morrison Aug 01 '13 at 01:51
  • Alright, that clears things up. I added a second part to my original question, would you mind answering that too? – Shaku Aug 01 '13 at 02:00
0

The new keyword is creating an anonymous object.

This is useful, when you want to create a instance that only use once.

ThiepLV
  • 1,219
  • 3
  • 10
  • 21