加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为数组分配然后使用构造函数

发布时间:2020-12-15 02:01:55 所属栏目:Java 来源:网络整理
导读:Person. java public class Person {? ? public String firstName,lastName;? ? public Person(String firstName,? ? ? ? ? ? String lastName) {? ? ? ? this.firstName = firstName;? ? ? ? this.lastName = lastName;? ? }? ? public String getFullName(
Person. java

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());
? ? ? ? }
? ? }
}

在上面的代码中,我们使用了两次“new”.这段代码是正确还是错误?第一个用于分配数组.但为什么第二个呢?这是来自讲义.

解决方法

是的,这是正确的.

这条线:

Person[] people = new Person[20]

在行中分配数组,充满对null的引用:

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

通过实例化Person类型的对象并在数组中分配引用来填充它[数组].

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读