Java Bootcamp – Workbooks and Challenges

Contacts – Part 2

In this workbook, you will finalize the Contact class.

Task 1 – Getters and Setters

You can autocomplete the getters and setters using Visual Studio Code Intellisense. However, setBirthDate and setAge will not have default implementations.

Task 1.1 – setAge

Make setAge private. The caller should not be allowed to access it. The birthDate they pass should automatically determine the age.

Task 1.2 – setBirthDate

  • After updating the birthDate field, use the SimpleDateFormat class to parse a MM/dd/yyyy String into an age (already done in Part 1).

  • The parse method from SimpleDateFormat throws a checked exception.

  • It's the caller's job to handle the failure. So, do not try-catch inside the setter.

  • Instead, throw the exception from the setter so that whoever is calling it handles the failure.

  • Call setAge from setBirthDate.

Task 1.3 – toAge

If you copied/pasted the code from Part 1 to achieve Task 1.2, I encourage you to create a toAge function instead:

     * Name: toAge
     * @param birthDate
     * @return age (int)
     * @throws ParseException
     * Inside the function:
     *   1. Parses a date from the birthDate String
     *   2. Gets the current date
     *   3. Subtracts the difference and returns the age.

Then, call toAge from the constructor and from setBirthDate.

Task 2 – Copy Constructor

To avoid the reference trap, we need a way to copy Contact objects. So, add a copy constructor.

Task 3 – toString

Every class that models an object should have a toString method.

Add a toString method to your class, and return a String that adheres to this format:

return "Name: " + <name> + "\n" +

"Phone number: " + <phone number> + "\n" +

"Birth Date: " + <birth date> + "\n" +

"Age: " + <age> + " year old\n";

Task 4 – Test your code.

  • Inside main(), print the object from Part 1.

Example output:

Example output for a malformed birthdate.

Good Luck!

Feedback Summary
43 students





Written Reviews
There are no written reviews yet.