_The so-called object array means that it contains a group of related objects, but in the use of the object array, the reader must be clear: the array must open up space, but because it is a reference data type, so each object in the array is a null value, then each object in the array must be instantiated separately when it is used.
Object array declaration:
Class object array name [] = new class [array length];
Example 1 code: dynamic initialization of object arrays
package self.learn.objectarray; public class Person { // Define Person class private String name; public Person() { } public Person(String name) { this.name = name; } public String getName() { // Get the name return this.name; } }
package self.learn.objectarray; public class ObjectArrayDemo { public static void main(String[] args) { Person per[] = new Person[3]; // Declare an array of objects // Every element is the default value before the object array is initialized System.out.println("=============== Array declaration ================"); for(int i = 0; i < per.length; i++) { System.out.print(per[i]+","); } // Each element in the array is initialized separately, each of which is an object and needs to be instantiated separately. per[0] = new Person("Zhang San"); per[1] = new Person("Li Si"); per[2] = new Person("Wang Wu"); System.out.println("\n=============== Object instantiation ================"); for(int i = 0; i < per.length; i++) { System.out.print(per[i].getName()+","); } } }
Operating results screenshot:
Like array initialization, object arrays can be divided into static initialization and dynamic initialization. The above operation is the dynamic initialization of arrays. The static initialization code is as follows:
Example 2 code: Statically initialize an array of objects
package self.learn.objectarray; public class ObjectArrayDemo { public static void main(String[] args) { Person per[] = {new Person("Zhang San"),new Person("Li Si"),new Person("Wang Wu")}; // Declare an array of objects System.out.println("=============== Array output ================"); for(int i = 0; i < per.length; i++) { System.out.print(per[i].getName()+","); } } }
Operating results screenshot:
The String args [] in the main method is an array of objects.
In the main method, String args [] can be used to receive initialization parameters. In fact, the String itself is a class, so the parameters in the main method itself appear as an array of objects.