这是一个家庭作业。 我必须执行以下操作:
private Date dateCreated which store, when the object was created.
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 字段时)
最佳答案
您可以在 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()
应该会为您提供所需的值。
关于java - Java创建对象时如何实现日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7703672/