以下代码可以成功编译,没有任何编译错误,但是如何使用带有接口名称的新关键字为接口创建Array(object)。 可以为实现类创建对象,并可以通过类似
的接口进行引用interface MyInterface{}
class MyClass1 implements MyInterface{}
class MyClass2 implements MyInterface{}
class Test{
MyInterface[] interfaceArray=new MyClass1[7]; //Valid reason
}
现在另一种情况是为接口本身创建对象。
interface MyInterface{}
class MyClass1 implements MyInterface{}
class MyClass2 implements MyInterface{}
class Test{
MyInterface[] interfaceArray=new MyInterface[7]; /*instantiating interface here, How is it possible?*/
}
请说明出现异常行为的原因
答案 0 :(得分:0)
这是正确的行为。 MyInterface[] interfaceArray=new MyInterface[7];
仅实例化一个数组长度为7
,该数组长度将容纳每个项应为MyInterface
的实例的项。
之后,您可以编写interfaceArray[0]=new MyInterface(){};
现在,您必须实现您的接口(请参见大括号)。
您可能基于Java中使用运算符new
的含糊之处而产生误解。用于实例化类(获取实例)和声明数组(为其分配内存)。