分配数组,然后使用构造 [英] allocating for array and then using constructor

查看:141
本文介绍了分配数组,然后使用构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Person {
    public String firstName, lastName;

    public Person(String firstName,
            String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFullName() {
        return(firstName + " " + lastName);
    }
}

PersonTest.java

public class PersonTest {
    public static void main(String[] args) {
        Person[] people = new Person[20];              //this line .
        for(int i=0; i<people.length; i++) {
            people[i] = 
                new Person(NameUtils.randomFirstName(),
                        NameUtils.randomLastName());  //this line
        }
        for(Person person: people) {
            System.out.println("Person's full name: " +
                    person.getFullName());
        }
    }
}

在上面code,我们用了两次新。这是code是正确的还是错误的?第一种是阵列的配置。但是,为什么第二个?这是一个从讲义。

In above code, we used twice "new". Is this code is correct or wrong? First one is for allocation of array. But why the second one? It's from lecture notes.

推荐答案

是的,这是正确的。

行:

Person[] people = new Person[20]

分配阵列,全额,而该行的引用:

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.

这篇关于分配数组,然后使用构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆