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)

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top