declare array of objects java code example
Example 1: array objects java
obj array[] = new obj[10];
for (int i = 0; i < array.length; i++) {
array[i] = new obj(i);
}
Example 2: java initialize object array
import java.util.stream.Stream;
class Example {
public static void main(String[] args) {
int len = 5;
Foo[] arr = Stream.generate(() -> new Foo(1))
.limit(len)
.toArray(Foo[]::new);
}
class Foo {
public int bar;
public Foo(int bar) {
this.bar = bar;
}
}
}
Example 3: how to make array of objects in java and use it
class enemies {
int marks;
}
enemies[] enemiesArray = new enemies[7];
enemiesArray[5] = new enemies(95);