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

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

问题描述

interface TestA {
    String toString();
}

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

结果是什么?

A。 test

B. null

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天全站免登陆