Skip Top Navigation Bar

Veterinary Office Simulation - Pattern Matching Mini-Lab

This lab will simulate a vet office and guide you through learning about pattern matching in Java.

This series of missions require you to write program code to use the following topics. Tutorials for available topics have been linked.

Mission 1

  1. Add a Dog record with meaningful names for the Dog's name, breed, and weight.
  2. Add a Dog object in the main method and print the value to the screen.

Mission 2

  1. Add a LicenseName record that consists of an show name and nickname for a dog.
  2. Modify the Dog record to include the LicenseName, breed, and weight.
  3. Update your Dog object to include a new LicenseName with the show name and nickname of your dog.

Mission 3

  1. Add a Cat record that consists of the cat's name, breed, and weight.
  2. Add a Cat object in the main method and print the value to the screen.
  3. Now we want to add our animals to an ArrayList. In order to do this, we need an Animal interface. You can create a sealed interface that identifies what classes are allowed to implement it, by using sealed interface Animal permits Dog, Cat {}
  4. Modify both the Dog and Cat records to implement the Animal interface by adding implements Animal after the parameter list.
  5. Create an ArrayList of Animal and add your Dog and Cat objects to the list.
  6. Print out your list.

Mission 4

  1. For each Animal in the list print out their name. If the animal is a Dog print the dog's show name. If the animal is a Cat print the cat's name.
  2. If you didn't do so in the prior part of this mission,update your code to use pattern matching with instanceof to combine the test, declaration, and typecasting into one statement.

Mission 5

  1. Consider a list with many different types of animals beyond just Dog and Cat. We could continue our if branching, but a better way would be to use a switch statement instead. Because we created Animal as a sealed interface we do not need to include a default branch to our switch statement.

Mission 6

  1. We can use unnamed variables and pattern matching to store the name instance variables for both the Dog and Cat objects. You can do this by changing the case statement to case Dog(LicenseName name, _, _):. Since we aren't using the values of breed and weight we do not need to store them.

Additional Optional Missions

  1. Update the switch case to use lambda notation.
  2. Update the Animal interface to permit additional animals of your choice.
  3. Add a record for your new animal.
  4. Create additional objects of your new Animal type record and add them to your ArrayList.
  5. Update your switch statement to deal with your new Animal object, making the switch statement exhaustive.