Interface Question

I know you cannot create a new instance of an Interface like you do an object, for example: x = new EventListener();, where EventListener is an Interface. But I've seen in the tutorials and in NetBeans, when adding action events to components, they have the following code as an example:

txtBrowserURI.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

onLaunchBrowser(null);

}

});

Notice they have "new ActionListener()", which is an Interface. Can this be done since they are implementing it's defined method at the same time?

Thank you.

[625 byte] By [lucci001a] at [2007-11-27 7:13:04]
# 1
Good intuition! For more formal explanations search for"anonymous inner classes".
baftosa at 2007-7-12 19:04:00 > top of Java-index,Java Essentials,New To Java...
# 2
Indeed, it can be done when you implement the whole interface that way. This is also called an "anonymous" class and it will generate a class file named that way:Myclass$1.class
Dalzhima at 2007-7-12 19:04:00 > top of Java-index,Java Essentials,New To Java...
# 3

It's called an anonymous inner class. We're defining the class that implements the interface right there, inline.

http://www.roseindia.net/javatutorials/anonymous_innerclassestutorial.shtml

http://www.javaranch.com/campfire/StoryInner.jsp

If you don't like those, you can google for more.

jverda at 2007-7-12 19:04:00 > top of Java-index,Java Essentials,New To Java...
# 4
Another tutorial link: http://java.sun.com/docs/books/tutorial/uiswing/events/generalrules.html
Hippolytea at 2007-7-12 19:04:00 > top of Java-index,Java Essentials,New To Java...