I have an interface.
public interface Module {
void init();
void actions();
}
What happens when i try to create an array like this?
Module[] instances = new Module[20]
How can i implement this array?
I have an interface.
public interface Module {
void init();
void actions();
}
What happens when i try to create an array like this?
Module[] instances = new Module[20]
How can i implement this array?
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?
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();
}
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();
}
}
To clarify accepted answer from @Burna, this array can be used to arrange collection of object, but it can never arrange its own interface in the collection, that is to put Module
interface in instances
reference variable. In JLS Chapter 10.6
Each variable initializer must be assignment-compatible (§5.2) with the array's component type, or a compile-time error occurs.
But you can't use the interface Module
in the initialization, because interface can't be instantiated (by definition). Thus you have to implement it first and arrange it in the array.