如何在Java中的构造函数中初始化引用属性? [英] How to initialize a reference attribute in a constructor in Java?

查看:350
本文介绍了如何在Java中的构造函数中初始化引用属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向一个类Person添加一个实例变量,该类是一个引用类型(Date,我写了一个类)。在我的Person类的构造函数中,因此我试图使用Date类的构造函数初始化Date属性,但是我不确定如何做。以前,我只有初始化基本类型(或Strings),如下所示。这是我的代码段。我不确定如何初始化生日,以便它使用Date类的构造函数。感谢!

I'm adding an instance variable to a class "Person" which is a reference type ("Date", which I have written a class for). In the constructor for my Person class, I am therefore trying to initialize the Date attribute using the constructor of the Date class, but I am unsure how to do this. Previously I have only ever initialized primitive types (or Strings), as seen below. This is a segment from my code. I'm unsure how to initialize "birthday" so that it uses the constructor of the Date class. Thanks!

public class Person {

/* Attribute declarations */
private String lastName;    // last name
private String firstName;   // first name
private String email;       // email address
private Date birthday;  // birth date

/**
 * Constructor initializes the person's name, email address, and birthday
 */
public Person(String firstName, String lastName, String email, Date birthday) {
    this.firstName = firstName;
    this.lastName = lastName;       
    this.email = email;
    this.birthday = ????


推荐答案

您是否要初始化 this.birthday 在使用Date构造函数的Person的构造函数中?然后使用 new 关键字:

Are you saying you want to initialize this.birthday in the constructor of Person using the Date constructor? Then use the new keyword like this:

this.birthday = new Date(<arguments if any exist>);

new 调用对象的构造函数。如果是这样,您不需要Person的 Date birthday 构造函数参数,除非您将其用于其他方面。

new calls the constructor of an object. If that's the case, you do not need the Date birthday constructor argument for Person, unless you use it for something else.

这篇关于如何在Java中的构造函数中初始化引用属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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