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
- Add a
Dog
record with meaningful names for the Dog's name, breed, and weight.
- Add a
Dog
object in the main method and print the value to the screen.
Mission 2
- Add a
LicenseName
record that consists of an show name and nickname for a dog.
- Modify the
Dog
record to include the LicenseName
, breed, and weight.
- Update your
Dog
object to include a new LicenseName
with the show name and nickname of your dog.
Mission 3
- Add a
Cat
record that consists of the cat's name, breed, and weight.
- Add a
Cat
object 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 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 {}
- Modify both the
Dog
and Cat
records to implement the Animal
interface by adding implements Animal
after the parameter list.
- Create an
ArrayList
of Animal
and add your Dog
and Cat
objects to the list.
- Print out your list.
Mission 4
- 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.
- 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
- 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
- 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
- Update the switch case to use lambda notation.
- Update the
Animal
interface to permit additional animals of your choice.
- Add a record for your new animal.
- Create additional objects of your new
Animal
type record and add them to your ArrayList
.
- Update your switch statement to deal with your new
Animal
object, making the switch statement exhaustive.