2

http://www.java2s.com/Code/Java/Event/PropertyChangeListenerSample.htm

(Java)

In the above example, I noticed the line

PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {

by itself, this wouldn't make sense, as PropertyChangeListener (java.beans.PropertyChangeListener) is an interface, and is therefore not instantiable.

However, right after, it seems a class that implements PropertyChangeListener is being written, without ever making a class keyword statement. I've never encountered this syntax before.

What is this syntax called, and how do I use it properly? Also, can anyone give me more examples of it? I'm not sure exactly what to google, so any leads would be helpful.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
romnempire
  • 87
  • 6

3 Answers3

2

This is an instance of an anonymous inner class.

An anonymous inner class is a class that does not have its own unique class name (as you noticed, it is just named by the implemented interface). The anonymous inner class also has access to any final variables in the method in which it is declared.

justkt
  • 14,610
  • 8
  • 42
  • 62
1

Anonymous inner class (From Wikipedia)

Anonymous inner classes are also used where the event handling code is only used by one component and therefore does not need a named reference.

This avoids a large monolithic actionPerformed(ActionEvent) method with multiple if-else branches to identify the source of the event. This type of code is often considered messy and the inner class variations are considered to be better in all regards.

It's mostly used (in AWT) when developers want to write their own ActionEvent for and ActionListener and EventListener.

You can also find it in java.util.Vector elements() method which has an anonymous inner class of Enumerable.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
0

This is Called Anonymous inner Class...See this question for more details in inner classes

Community
  • 1
  • 1
Mohamad Alhamoud
  • 4,881
  • 9
  • 33
  • 44