Java SE 8 API documentation

Last modification: 26/09/2016

Exercises

  1. Create a class named Person. For each person we keep record of the first name, last name (two Strings) and year of birth (int).

    Make a constructor as well, which takes the initial values of the fields as arguments.

    1. Add an isAdult method, which takes a year as argument and returns true if the person is adult in the given year, false otherwise.

    2. Create a way to convert a Person into string. For this reason, add a method toString, which returns the first name and the last name separated by a space in a string.

    3. Add a boolean class field, which controls whether or not the toString returns the name in upper case. One field should influence all instances.

  2. Create a class named Car. For each car we keep record of the licence number (String), number of doors (int) and the owner (Person).

    Make a constructor as well, which initialises the fields.

    1. Add an isFamilyCar method, which decides whether the car is a family car or not, that is, whether it has 5 doors.

    2. Add an isValid method, which returns true if and only if the following holds:

      • the licence number is not empty string (use String.isEmpty() to check)
      • the number of doors is either 3 or 5
      • the owner is not an empty reference, that is, it is not null
      • the owner is adult in this year
    3. Add a toString method, which converts the car into a string. For instance, the car with licence number "ABC-123", 5 doors and owned by Roger Federer is converted to the following string:

      "ABC-123 5 doors, owner: Roger Federer"
  3. Create a package named city and move the above classes into it.

  4. Write a main method, which creates instances of Person and Car and prints them to the standard output.

  5. Turn the constructor of Person into a makePerson static method. The method should instantiate the Person and initialise its fields.

    Check that the arguments are valid: the name must not be empty and the year of birth must be between 1900 and 2016. If the conditions do not hold, then return null.