为什么Java接口可以在这些代码中实例化? [英] Why Java interface can be instantiated in these codes?

查看:166
本文介绍了为什么Java接口可以在这些代码中实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

创建对象


我是Java新手。根据我的理解:




  • 我们不能实例化接口。我们只能实例化实现接口

  • code> new 关键字用于从类创建对象。



我读了一些Java程序的源代码,我发现有时一个接口被实例化。例如:



示例1:

  JButtonObject.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// codes
}
}

示例2:


$ b b

  SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
// codes
}
});

在上面的示例中,ActionListener和Runnable都是Java接口。我可以知道为什么可以在这些代码中实例化



实例化接口的目的是什么?请参阅此示例,似乎我们应该创建一个实例

解决方案

代码不实例化一个接口,而是一个匿名类,实现 ActionListener Runnable


匿名类是没有名称的本地类。匿名类
使用
new 运算符在单个简明表达式中定义和实例化。


代码是匿名创建 ActionListener 的实例,这意味着该类实际上没有任何名称。



编译该类后,您可以在输出中看到一个类 YourClass $ 1.class $ 1 仅仅意味着类是一个匿名类,而编号 1 是由编译器生成的。当你有两个匿名类时,在编译时会有类似 YourClass $ 1.class YourClass $ 2.class




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

这篇关于为什么Java接口可以在这些代码中实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆