creat a class array code example

Example 1: java initialize object array

import java.util.stream.Stream;

class Example {
  
  public static void main(String[] args) {
    int len = 5;  // For example.
    
    // Use Stream to initialize array.
    Foo[] arr = Stream.generate(() -> new Foo(1))  // Lambda can be anything that returns Foo. 
                      .limit(len)
                      .toArray(Foo[]::new);
  }
  
  // For example.
  class Foo {
    public int bar;

    public Foo(int bar) {
      this.bar = bar;
    }
  }
}

Example 2: java class array of objects

public class MainClass
{  
    public static void main(String args[])
    {
        System.out.println("Hello, World!");
        //step1 : first create array of 10 elements that holds object addresses.
        Emp[] employees = new Emp[10];
        //step2 : now create objects in a loop.
        for(int i=0; i<employees.length; i++){
            employees[i] = new Emp(i+1);//this will call constructor.
        }
    }
}

class Emp{
    int eno;
    public Emp(int no){
        eno = no;
        System.out.println("emp constructor called..eno is.."+eno);
    }
}