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 aclasswhich implements aninterface. - The
newkeyword 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
ActionListenerorRunnable.The code is creating an instance of
ActionListeneranonymously, which means the class does not actually have any name.After compiling that class, you can see a class
YourClass$1.classin the output. The$1simply means that class is an anonymous class and the number1is generated by the compiler. When you have two anonymous classes, it will have something likeYourClass$1.classandYourClass$2.classin the compiled classes.See