Java中创建对象时如何实现日期?
这是一份家庭作业。 我必须实现以下内容:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在
Account
的构造函数中设置dateCreated
来捕获它的创建时间,如下所示:或者,您可以显式设置它(前提是您公开了一个 setter):
然后,您的 getter
getDateCreated()
应该为您提供所需的值。You can set the
dateCreated
in the constructor ofAccount
, to capture when it was created like this:OR, you could explicitly set it (provided you have a setter exposed):
Your getter
getDateCreated()
should then give you the desired value.如果您使用
它将用当前时间初始化。
If you use
it will be initialised with the current time.
只需在构造函数中通过 new Date() 创建日期即可。它使用您调用构造函数的时间创建一个日期。
Just create the Date in the constructor, via new Date(). It creates a Date with the time you called the constructor.