我们可以创建接口的对象吗? [英] Can we create an object of an interface?

查看:33
本文介绍了我们可以创建接口的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

interface TestA {
    String toString();
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new TestA() {
            public String toString() {
                return "test";
            }
        });
    }
}

结果如何?

A.测试
B. 空
C. 运行时抛出异常.
D. 第1行错误导致编译失败.
E. 第4行错误导致编译失败.
F. 第5行错误导致编译失败.

A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.

这个问题的答案是什么,为什么?关于这个问题,我还有一个疑问.在第 4 行中,我们正在创建 A 的对象.是否可以创建接口的对象?

What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?

推荐答案

您在这里看到的是 匿名内部类:

给定以下界面:

interface Inter {
    public String getString();
}

您可以像这样创建类似它的实例的东西:

You can create something like an instance of it like so:

Inter instance = new Inter() {
    @Override
    public String getString() {
        return "HI";
    }
};

现在,您有一个您定义的接口的实例.但是,你应该注意,你实际上所做的是定义了一个实现接口的类,同时实例化了这个类.

Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.

这篇关于我们可以创建接口的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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