【问题标题】:Creating Objects for the interface directly using new keyword直接使用 new 关键字为接口创建对象
【发布时间】:2023-04-05 16:40:01
【问题描述】:

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

请解释奇怪行为的原因

【问题讨论】:

  • 这里不是在实例化接口,而是在实例化一个数组类型,它恰好有一个接口作为组件类型。
  • @john,谢谢,能不能详细解释一下
  • 但是 new 关键字在使用时会返回一个对象,那么如何将 new 关键字与接口一起使用
  • 就像我说的,您没有在接口中使用new 关键字。 MyInterfaceinterface,但 MyInterface[] 不是。如果你检查MyInterface[].class.isInterface() 的返回值,你会看到它返回了false
  • @Jorn,谢谢 :)

标签: java oop inheritance interface


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2013-08-28
    相关资源
    最近更新 更多