问题
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