De Paul De Paul - 26 days ago 6
Java Question

Gregorian calender: Confusion with calling the method on the object

The program below is part of a tutorial.I have some confusion here
with the below lines:

GregorianCalendar gCal = new GregorianCalendar();
gCal.add(GregorianCalendar.YEAR, 1);
this.expiryDate = gCal.getTime();


shouldn't the above code be something like this:

GregorianCalendar gCal = new GregorianCalendar();
SomeDatatype variable = gCal.add(GregorianCalendar.YEAR, 1);
this.expiryDate = variable.getTime();


Following is the part of the original program:

package models;
import java.util.Date;
import java.util.GregorianCalendar;

import utilities.GenderType;


public class Customer {

private String title;
private String firstName;
private String surname;
private String address;
private String phoneNumber;
private String email;
private int customerNumber;
private GenderType gender;
private boolean isvalid;
private Date expiryDate;

public Customer(String title, String firstName, String surname, String address,
String phoneNumber, String email, int customerNumber, GenderType gender) {

setName(title, firstName, surname);
this.address = address;
this.phoneNumber=phoneNumber;
this.email = email;
this.customerNumber = customerNumber;
this.gender = gender;
this.isvalid = true;
GregorianCalendar gCal = new GregorianCalendar();
gCal.add(GregorianCalendar.YEAR, 1);
this.expiryDate = gCal.getTime();
}
}

Answer

In GregorianCalendar class, add() method returns void.

The reason for this is that it performs an action on the internal data of the GregorianCalendar. It adds the defined portion of time to it.

You don't need to get something returned from add() method. The same object is already updated after calling it, so, you only have to get the new time value it contains.

See GregorianCalendar add() method reference.