Array of Interface in Java

后端 未结 5 867
自闭症患者
自闭症患者 2020-12-24 09:15

I have an interface.

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

What happens when i try to create an array li

5条回答
  •  抹茶落季
    2020-12-24 09:50

    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();
     }
    }
    

提交回复
热议问题