Java中的接口数组

我有一个界面。

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

当我尝试创建这样的数组时会发生什么?

 Module[] instances = new Module[20] 

我该如何实现这个数组?

对的,这是可能的。 您需要使用Type Module对象填充数组的字段

instances[0] = new MyModule();

MyModule是一个实现Module接口的类。 或者,您可以使用匿名内部类:

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

这回答了你的问题了吗?

您需要使用实现该接口的类的实例填充数组。

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

您需要创建一个具体的类类型来实现该接口并在数组创建中使用它

当然,您可以创建一个类型为接口的数组。 在使用其中的元素之前,您只需将对该接口的具体实例的引用放入数组中,使用名称或匿名创建。 下面是一个打印数组对象哈希码的简单示例。 如果你试图使用任何元素,比如myArray [0] .method1(),你得到一个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(); } }