Java Reference
In-Depth Information
}
 
public Person(String name) {
this(name, 1900, 1, 1);
}
 
public int calculateAge() {
Period p = Period.between(this.birthdate, LocalDate.now());
return p.getYears();
}
 
public int calculateAge(LocalDate date) {
Period p = Period.between(this.birthdate, date);
return p.getYears();
}
 
public int calculateAge(int year, int month, int day) {
Period p = Period.between(this.birthdate,
LocalDate.of(year, month, day));
return p.getYears();
}
}
How It Works
Here's how this example works:
1.
In the first constructor method, you used the this keyword to initialize the variables of “this” object being
created. You also used the LocalDate.of() method to assign a date variable from three int values.
2.
In the second constructor, you used the this keyword to use the first constructor of “this” class,
but you filled in default values for year, month, and day.
3.
In the first calculateAge() method, you used the LocalDate.now() method to compare a person's
birthdate (using the this keyword) to the current date. Period and Period.getYears() handled
the calculation for you, as they are defined as part of the date and time facilities added to Java 8.
4.
In the second calculateAge() method, with a LocalDate parameter, you used a similar format
to the first, but you used a specified date instead of the current date. You could change the first
calculateAge() method to use this one in the following way:
public int calculateAge() {
return calculateAge(LocalDate.now());
}
5.
In the third calculateAge() method, with three int parameters, you used a similar format to the
other two, but this time you called the LocalDate.of() method to get the correct date from the
integers specified. Again, you could use the second calculateAge() method to rewrite this one in
a simpler and more robust way:
public int calculateAge(int year, int month, int day) {
return calculateAge(LocalDate.of(year, month, day));
}
Search WWH ::




Custom Search