Array of Interface in Java

后端 未结 5 857
自闭症患者
自闭症患者 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 10:01

    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.

提交回复
热议问题