【发布时间】: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关键字。MyInterface是interface,但MyInterface[]不是。如果你检查MyInterface[].class.isInterface()的返回值,你会看到它返回了false。 -
@Jorn,谢谢 :)
标签: java oop inheritance interface