Java Reference
In-Depth Information
2.
Create a new class by right‐clicking on the src folder in your new project. Select New and then
Class. Name the new class Person . Uncheck the box to create a main method. This class should
look like this:
public class Person {
 
}
3.
Add the following instance variables to your class:
String name;
LocalDate birthdate;
4.
In order to use LocalDate , you need to import the java.time package. Add the following
statement above your class heading, or click the error notification and double‐click the import
suggestion.
5.
Add a constructor method to set up new Person objects. Your constructor should accept the one
String parameter for name and three int parameters for the year, month, and day of the birthdate.
Include a statement inside the constructor to convert the int s to a LocalDate type. Assign the val-
ues to the instance variables. Your four‐parameter constructor should look like this:
public Person (String name, int year, int month, int day){
LocalDate tempBD = LocalDate.of(year, month, day);
this.name = name;
this.birthdate = tempBD;
}
6.
Overload the constructor by creating a second one with only name . Suppose this is used when you
don't know someone's birthdate. Use the this keyword, with default values where needed.
7.
Create a method to calculate someone's age. LocalDate has a method called now() that returns the
current date. To calculate the period between two dates, use the following statements:
Period p = Period.between(date1, date2);
int age = p.getYears();
8.
Overload the calculateAge() method by adding another method with the same name, but with a
LocalDate parameter to calculate a person's age on a certain date. Make another one that accepts
three int s for year, month, and day.
9.
Your Person class should look something like this:
import java.time.*;
 
public class Person {
String name;
LocalDate birthdate;
 
public Person(String name, int year, int month, int day) {
this.name = name;
this.birthdate = LocalDate.of(year, month, day);
Search WWH ::




Custom Search