Array of Interface in Java
You need to create a concrete class type that would implement that interface and use that in your array creation
Of course you can create an array whose type is an interface. You just have to put references to concrete instances of that interface into the array, either created with a name or anonymously, before using the elements in it. Below is a simple example which prints hash code of the array object. If you try to use any element, say myArray[0].method1(), you get an NPE.
public class Test {
public static void main(String[] args) {
MyInterface[] myArray = new MyInterface[10];
System.out.println(myArray);
}
public interface MyInterface {
void method1();
void method2();
}
}
You would need to fill the array with instances of a class(es) that implement that interface.
Module[] instances = new Module[20];
for (int i = 0; i < 20; i++)
{
instances[i] = new myClassThatImplementsModule();
}
yes, it is possible. You need to fill the fields of the array with objects of Type Module
instances[0] = new MyModule();
And MyModule
is a class implementing the Module interface. Alternatively you could use anonymous inner classes:
instances[0] = new Module() {
public void actions() {}
public void init() {}
};
Does this answer your question?