Why Java interface can be instantiated in these codes? [duplicate]

不问归期 提交于 2019-12-01 08:38:30

问题


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.


回答1:


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

  • Anonymous Classes



回答2:


Above example does not create new instance of interface - after new keyword there is implementation method for current interface. Read more about anonymous class.




回答3:


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.



来源:https://stackoverflow.com/questions/11069056/why-java-interface-can-be-instantiated-in-these-codes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!