Array of Interface in Java

后端 未结 5 851
自闭症患者
自闭症患者 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:45

    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?

    0 讨论(0)
  • 2020-12-24 09:48

    You need to create a concrete class type that would implement that interface and use that in your array creation

    0 讨论(0)
  • 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();
     }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 10:09

    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();
    }
    
    0 讨论(0)
提交回复
热议问题