Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Interface in Java

I have an interface.

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

What happens when i try to create an array like this?

Module[] instances = new Module[20]

How can i implement this array?

like image 950
Rog Matthews Avatar asked Feb 13 '12 05:02

Rog Matthews


People also ask

Can you create an array of interface in Java?

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.

Can you make an array of interface?

Arrays of interfaces can be declared to provide a multiple connections between tasks. Individual elements of the array can be passed to tasks or the whole array can be passed on. In the following example, the array is passed to task3 which connects to both task1 and task2.

Can you have an ArrayList of interface?

List is a Java interface that describes a sequential collection of objects. ArrayList is a class that describes an array-based implementation of the List Java interface. A new instance of the ArrayList class is obtained and assigned to List variable names .

How do you define an array of interfaces?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.


1 Answers

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?

like image 126
burna Avatar answered Oct 11 '22 16:10

burna