How Implement Date when the object created in Java?

blaces picture blaces · Oct 9, 2011 · Viewed 8k times · Source

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)

Answer

Saket picture Saket · Oct 9, 2011

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.