Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

java - How do I create a default constructor including a Date as type Date?

In my Java College Class, I have to create the class Customer. A customer has to have a first name, the last name, a birthday and an address.

The problem I have is to fill the default constructor since I have to assign a value to birthday. But I don't know how to do it. If I try to write birthday = (1999,1,1) it throws an error and asks me if I want to convert birthday to int.

My code:

import java.util.Date;

public class Customer {
    private String firstName, lastName;
    private Date birthday;
    private String address;

    public Customer() {
        firstName = "Hans";
        lastName = "Meier";
        //birthday = ? 
        address = "-";
    }

    public Customer(String firstName, String lastName, Date birthday, String address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthday = birthday;
        this.address = address;
    }

    public Customer(Customer customer) {
        firstName = customer.firstName;
        lastName = customer.lastName;
        birthday = customer.birthday;
        address = customer.address;
    }
}
question from:https://stackoverflow.com/questions/65861405/how-do-i-create-a-default-constructor-including-a-date-as-type-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

If you do not have to deal with timezone, you can use LocalDate:

private LocalDate birthday;

and then, you can use

birthday = LocalDate.of(1999, 1, 1);

If you want to put timezone information, you can use ZonedDateTime e.g.

ZoneId zoneId = ZoneId.of("Europe/London");
ZonedDateTime birthday = ZonedDateTime.of(LocalDateTime.of(1999, 1, 1, 22, 10), zoneId);

Learn more about the modern date-time API from Trail: Date Time.

FYI: Most of the methods, including the constructors, of java.util.Date are deprecated. If you want to create an object of Date with some given year, month and day, you should use Calendar as shown below:

Calendar calendar = Calendar.getInstance();
calendar.set(1999, 0, 1);
Date birthday = calendar.getTime();

Note that the month in java.util date-time API is 0-based i.e. for January, you have to use 0, for February, you have to use 1 and so on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...