1

这是一个家庭作业。我必须执行以下操作:

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 字段时)

4

3 回答 3

3

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

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

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

于 2011-10-09T13:05:32.337 回答
1

如果你使用

private Date dateCreated = new Date();

它将使用当前时间初始化。

于 2011-10-09T13:05:33.913 回答
0

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

于 2011-10-09T13:06:16.303 回答