allocating for array and then using constructor

后端 未结 3 865
终归单人心
终归单人心 2021-01-21 05:23

Person.java

public class Person {
    public String firstName, lastName;

    public Person(String firstName,
            String lastName) {
        this.firstN         


        
相关标签:
3条回答
  • 2021-01-21 05:56
    Person[] people = new Person[20];
    

    only allocates memory for objects Person (filled with nulls). Then you need to fill it with particular Persons (with random name and surname int this example).

    0 讨论(0)
  • 2021-01-21 06:05

    Yes, it is correct.

    The line:

    Person[] people = new Person[20]
    

    allocates the array, full of references to null while the line:

    new Person(NameUtils.randomFirstName(),
                          NameUtils.randomLastName());  //this line
    

    fills it [the array] by instantiating objects of type Person, and assigning the reference in the array.

    0 讨论(0)
  • 2021-01-21 06:19

    new Person[20] creates an array that can hold 20 references to Person objects. It does not create any actual Person objects.

    new Person(...) creates a Person object.

    The critical distinction to make here is that unlike in C or C++, new Person[20] does not allocate memory for 20 Person objects. The array does not contain the actual objects; it only contains references to them.

    0 讨论(0)
提交回复
热议问题