• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instantiating an Interface?  RSS feed

 
Skye Antinozzi
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a snippet here that I'm working with and I have a few questions about it.



My questions are:

1. How is it possible to use new on ActionListener when ActionListener is an Interface, not a Class. Isn't it illegal to instantiate an Interface?

2. What is going on with the argument to addActionListener? We have the new ActionListener, but we also have a method being defined as well? Can anybody shed some light on this so I may better understand it?

In addition, I understand what this does. I've actually used it for a while now but I've never questioned how it works when it is used this way.
Thanks in advance!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not instantiating an interface - you're declaring an anonymous inner class on the spot and you create an instance of that.

If you're using Java 8, you can use a lambda expression instead of an anonymous inner class:
 
Skye Antinozzi
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh okay that makes sense then. I suppose that answers my first question and also my second. Thank you very much!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!