This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
Creating an “object” of an interface
I am new to Java. Based on my understanding:
- We cannot instantiate an
Interface
. We can only instantiate a class
which implements an interface
.
- The
new
keyword is used to create an object from a class.
However, when I read the source codes of some Java programs, I found that sometimes an Interface is instantiated. For example:
Example 1:
JButtonObject.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//codes
}
});
Example 2:
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//codes
}
});
In the example at above, ActionListener and Runnable are both Java interface. May I know why they can be instantiated in these codes?
What is the purpose of instantiating an Interface? Refer to this example, it seems that we should create an instance of a class which implement the interface.
That code does not instantiate an interface, but rather an anonymous class which implements ActionListener
or Runnable
.
An anonymous class is a local class without a name. An anonymous class
is defined and instantiated in a single succinct expression using the
new operator.
The code is creating an instance of ActionListener
anonymously, which means the class does not actually have any name.
After compiling that class, you can see a class YourClass$1.class
in the output. The $1
simply means that class is an anonymous class and the number 1
is generated by the compiler. When you have two anonymous classes, it will have something like YourClass$1.class
and YourClass$2.class
in the compiled classes.
See
Above example does not create new instance of interface - after new keyword there is implementation method for current interface. Read more about anonymous class.
This form is just a shorthand to make it easier to create an object that implements an Interface. It's not the interface itself being instantiated, but rather an Object implements Runnable
for example.