使用new关键字直接为接口创建对象 [英] Creating Objects for the interface directly using new keyword
问题描述
以下代码可以成功编译,没有任何编译错误,但是如何使用带有接口名称的新关键字为接口创建Array(object). 可以为实现类创建对象,并可以通过类似
The following code compiles successfully without any compilation errors but how can we create Array(object) for Interface using new Keyword with the interface name. Objects can be created for the implementing class and can be referred by the interface like
interface MyInterface{}
class MyClass1 implements MyInterface{}
class MyClass2 implements MyInterface{}
class Test{
MyInterface[] interfaceArray=new MyClass1[7]; //Valid reason
}
现在另一种情况是为接口本身创建对象.
Now the other case is creating object for the Interface itself.
interface MyInterface{}
class MyClass1 implements MyInterface{}
class MyClass2 implements MyInterface{}
class Test{
MyInterface[] interfaceArray=new MyInterface[7]; /*instantiating interface here, How is it possible?*/
}
请说明出现异常行为的原因
Please explain the reason for the strange behaviour
推荐答案
这是正确的行为. MyInterface[] interfaceArray=new MyInterface[7];
仅实例化一个长度为7
的数组,该数组长度将保存每个项应为MyInterface
的实例的项.
之后,您可以编写interfaceArray[0]=new MyInterface(){};
现在,您必须实现您的接口(请参见大括号).
您可能基于Java中使用运算符new
的含糊之处而产生误解.用于实例化类(获取实例)和声明数组(为其分配内存).
That is the right behavior. MyInterface[] interfaceArray=new MyInterface[7];
ONLY instantiate an array length of 7
which will hold the items each one should be an instance of MyInterface
.
After that, you are able to write interfaceArray[0]=new MyInterface(){};
And now you must implement your interface (see the curly brackets).
Probably, you misunderstanding based on a slightly ambiguous using operator new
in Java. It is used to instantiate the classes (getting their instances) and declaring arrays (allocating memory for them).
这篇关于使用new关键字直接为接口创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!