使用new关键字直接为接口创建对象

时间:2018-07-07 19:39:12

标签: java oop inheritance interface

以下代码可以成功编译,没有任何编译错误,但是如何使用带有接口名称的新关键字为接口创建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?*/
}

请说明出现异常行为的原因

1 个答案:

答案 0 :(得分:0)

这是正确的行为。 MyInterface[] interfaceArray=new MyInterface[7]; 实例化一个数组长度为7,该数组长度将容纳每个项应为MyInterface的实例的项。
之后,您可以编写interfaceArray[0]=new MyInterface(){}; 现在,您必须实现您的接口(请参见大括号)。
您可能基于Java中使用运算符new的含糊之处而产生误解。用于实例化类(获取实例)和声明数组(为其分配内存)。