Java中创建对象时如何实现日期?

发布于 2024-12-09 01:36:27 字数 735 浏览 4 评论 0原文

这是一份家庭作业。 我必须实现以下内容:

private Date dateCreated 在创建对象时存储。

private Date dateCreated;

dateCreated 的 getter 方法。

public Date getDateCreated() {
    return dateCreated;
}

并且必须实现这个主要方法:

public static void main(String[] args){
    Account a=new Account(1122,20000,4.5);
    a.withdraw(2500);
    a.deposit(3000);
    System.out.println(a.getBalance());
    System.out.println(a.getMonthlyInterestRate()+"%");
    System.out.println(a.getDateCreated()); // or another method what can get 
       //time  when the object created
}

我尝试使用 getTime() 但我不知道如何在我的代码中使用。 我看到了一些解决方案,但它总是为此创建另一个类。 我想要一个简单的解决方案。 (也许在声明 dateCreated 字段时)

It's an homework.
I have to implement the following:

private Date dateCreated which store, when the object was created.

private Date dateCreated;

getter method for dateCreated.

public Date getDateCreated() {
    return dateCreated;
}

And must implement this main method:

public static void main(String[] args){
    Account a=new Account(1122,20000,4.5);
    a.withdraw(2500);
    a.deposit(3000);
    System.out.println(a.getBalance());
    System.out.println(a.getMonthlyInterestRate()+"%");
    System.out.println(a.getDateCreated()); // or another method what can get 
       //time  when the object created
}

I've tried use the getTime() but I don't know how can I use in my code.
I saw some solution, but it always created an another classes for this.
I would like a simple solution. (maybe when declare the dateCreated field)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谈情不如逗狗 2024-12-16 01:36:27

您可以在 Account 的构造函数中设置 dateCreated 来捕获它的创建时间,如下所示:

public Account(...<params>...)
{
   ... <usual param initialization that you already have>  ...
   this.dateCreated = new Date(); // sets to the current date/time
}

或者,您可以显式设置它(前提是您公开了一个 setter):

a.setDateCreated(new Date());

然后,您的 getter getDateCreated() 应该为您提供所需的值。

You can set the dateCreated in the constructor of Account, to capture when it was created like this:

public Account(...<params>...)
{
   ... <usual param initialization that you already have>  ...
   this.dateCreated = new Date(); // sets to the current date/time
}

OR, you could explicitly set it (provided you have a setter exposed):

a.setDateCreated(new Date());

Your getter getDateCreated() should then give you the desired value.

喜爱纠缠 2024-12-16 01:36:27

如果您使用

private Date dateCreated = new Date();

它将用当前时间初始化。

If you use

private Date dateCreated = new Date();

it will be initialised with the current time.

花开半夏魅人心 2024-12-16 01:36:27

只需在构造函数中通过 new Date() 创建日期即可。它使用您调用构造函数的时间创建一个日期。

Just create the Date in the constructor, via new Date(). It creates a Date with the time you called the constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文