简体   繁体   中英

Setting an Object with Calender current Date

I have an issue where by my Vechicle Object is not having its date currently set to whatever today is. Strangely my test information Still comes out like this. All other functionality works fine with Calender.

Date Sold: Thu Jan 01 00:00:00 GMT 1970

Main Class

public void buyVechicle(String Vin){
    Vechicle V = findVechicle(Vin);
    if (V.getHasBeenSold() == true){
        System.out.print("This car has already been sold");
    }
    else{
        V.setHasBeenSold();
        V.setDateSold();
    }
}

Vechicle Class

public Calendar setDateSold(){
    Calendar cal = Calendar.getInstance();
    return cal;
}
public void setDateSold(){
    Calendar cal = Calendar.getInstance();
    this.dateSold = cal;
}

You have to set/assign the value in your class.

try

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
Calendar cal = Calendar.getInstance(); 
this.soldDate= dateFormat.format(cal.getTime());
 return cal;

this lets you manage the output dateformat aswel

update

also, you are not setting the state of the calling object. In your setter method set

   this.soldDate= dateFormat.format(cal.getTime());

this will save the sold date with object and you will be able to use it when you need it.

Your set method doesn't set any fields in the Vehicle class, so the other methods won't find that date you just set. Change it to this:

public Calendar setDateSold(){
    Calendar cal = Calendar.getInstance();
    this.dateSold = cal;
    return cal;
}

Java-bean setters usually have a value parameter and don't usually return values, so this would be more idiomatic:

public void setDateSold(Calendar calendar){
    this.dateSold = calendar;
}

To avoid confusing other Java programmers, used to Java-bean style setters, you could rename your method:

public Calendar sold(){
    this.dateSold = Calendar.getInstance();
    return this.dateSold;
}

The caller sends a message to the vehicle that effectively says "you've been sold".

Or, even better, have several methods to keep the behaviors separate:

private Calendar today() {
    return Calendar.getInstance();
}

public void sold(){
    setDateSold(today());
}

public Calendar getDateSold() {
    return this.dateSold;
}

private void setDateSold(Calendar calendar) {
    this.dateSold = calendar;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM