Veterinary Office Simulation - Pattern Matching Mini-Lab
This lab will simulate a vet office and guide you through learning about pattern matching in Java.
Required Knowledge
This series of missions require you to write program code to use the following topics. Tutorials for available topics have been linked.
- Introduction to Records
- Creating Record Objects and Calling Methods
- Sealed interfaces
- Introduction to List and ArrayList Objects
- Pattern matching for
instanceof - Exhaustive switch statements
- Unnamed variables and patterns
Missions
Mission 1
- Add a
Dogrecord with meaningful names for the Dog's name, breed, and weight. - Add a
Dogobject in the main method and print the value to the screen.
Mission 2
- Add a
LicenseNamerecord that consists of an show name and nickname for a dog. - Modify the
Dogrecord to include theLicenseName, breed, and weight. - Update your
Dogobject to include a newLicenseNamewith the show name and nickname of your dog.
Mission 3
- Add a
Catrecord that consists of the cat's name, breed, and weight. - Add a
Catobject in the main method and print the value to the screen. - Now we want to add our animals to an
ArrayList. In order to do this, we need anAnimalinterface. You can create a sealed interface that identifies what classes are allowed to implement it, by usingsealed interface Animal permits Dog, Cat {} - Modify both the
DogandCatrecords to implement theAnimalinterface by addingimplements Animalafter the parameter list. - Create an
ArrayListofAnimaland add yourDogandCatobjects to the list. - Print out your list.
Mission 4
- For each
Animalin the list print out their name. If the animal is aDogprint the dog's show name. If the animal is aCatprint the cat's name. - If you didn't do so in the prior part of this mission,update your code to use pattern matching with
instanceofto combine the test, declaration, and typecasting into one statement.
Mission 5
- Consider a list with many different types of animals beyond just
DogandCat. We could continue our if branching, but a better way would be to use a switch statement instead. Because we createdAnimalas a sealed interface we do not need to include a default branch to our switch statement.
Mission 6
- We can use unnamed variables and pattern matching to store the name instance variables for both the
DogandCatobjects. You can do this by changing the case statement tocase Dog(LicenseName name, _, _):. Since we aren't using the values ofbreedandweightwe do not need to store them.
Additional Optional Missions
- Update the switch case to use lambda notation.
- Update the
Animalinterface to permit additional animals of your choice. - Add a record for your new animal.
- Create additional objects of your new
Animaltype record and add them to yourArrayList. - Update your switch statement to deal with your new
Animalobject, making the switch statement exhaustive.