创建“对象”一个界面 [英] Creating an "object" of an interface

查看:113
本文介绍了创建“对象”一个界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我与一位声称可以创建界面对象的朋友发生了争执。当我说这是不可能的时候,他向我展示了以下一段代码,它看起来与匿名类似。现在的问题是,答案是什么?

Today I had a bit of an argument with a friend who claimed that an interface object can be created. When I said that it's impossible, he showed me the following piece of code, which seemed similar to anonymous classes.Now the question is, what's the right answer?

public interface I {
    public void f();
}

public class InterfaceTest {
    public static void main(String []args){
        new I(){
            @Override
            public void f() {
                System.out.println("HELLO");                
            }           
        };
    }
}

这真的可以称为创建接口对象 ?

Can this really be called creating an interface "object"?

推荐答案

不,这是创建一个实现接口的匿名类的实例。

No, this is creating an instance of an anonymous class that implements the interface.

以下是的明确答案Java语言规范,第15.9节


非限定和限定类实例创建表达式可以
结尾可选阶级身体。这样的类实例创建
表达式声明了一个匿名类(§15.9.5)并创建了一个
的实例。

Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (§15.9.5) and creates an instance of it.

这篇关于创建“对象”一个界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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