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?
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.
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.
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 .
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With