Interface Array in Java

I have an interface.

public interface Module { void init(); void actions(); } 

What happens when I try to create such an array?

 Module[] instances = new Module[20] 

How can I implement this array?

+7
source share
4 answers

Yes it is possible. You need to fill the array fields with objects of type Module

instances[0] = new MyModule();

And MyModule is a class that implements the module interface. Alternatively, you can use anonymous inner classes:

 instances[0] = new Module() { public void actions() {} public void init() {} }; 

Does this answer your question?

+23
source

You will need to populate the array with instances of the class (s) that implement this interface.

 Module[] instances = new Module[20]; for (int i = 0; i < 20; i++) { instances[i] = new myClassThatImplementsModule(); } 
+6
source

You need to create a specific class type that will implement this interface and use it in creating an array

+4
source

Of course, you can create an array whose type is an interface. You just need to put references to specific instances of this interface in an array created with a name or anonymously before using elements in it. The following is a simple example that displays the hash code of an array object. If you try to use any element, say myArray [0] .method1 (), you will get 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(); } } 
+1
source

All Articles