开发者

How Implement Date when the object created in Java?

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 cre开发者_如何转开发ated an another classes for this. I would like a simple solution. (maybe when declare the dateCreated field)


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.


If you use

private Date dateCreated = new Date();

it will be initialised with the current time.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜