Creating Objects for the interface directly using new keyword

无人久伴 提交于 2020-05-14 14:42:49

问题


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


回答1:


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).



来源:https://stackoverflow.com/questions/51226426/creating-objects-for-the-interface-directly-using-new-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!