Considering the amount of work required to get ready to add a resource, you might think that creating a hierarchy and then performing so-called polymorphic queries is difficult. It isn’t. The difficulty of moving towards supporting a hierarchy is that we started with a concrete class and wanted to later introduce an abstract concept, the Resource.
In this final step for the tutorial, we’ll create a second kind of resource, a DVD and then write some basic tests.
Supporting DVD’s
The first basic test is creating a dvd and checking it out to a Patron. This is a test we add to LibraryTest.java.
First test: Checkout a Dvd
This test uses a new constant, CURRENT_PLUS_6, here’s the change to LibraryTest to support that.
To get this to compile, we need to add support in the library class for creating a DVD. Here’s that basic support:
Updating Library
Notice that we have a director and a dvd in this example. Here are those classes:
Director.java
Dvd.java
Resource.java
To get this to actually work, we need to use the @Inheritance annotation on resource. Here’s the change:
As mentioned before, there are three kinds of representations for hierarchy. We are using the so-called JOINED approach, which means there is a table per class. It turns out that we need to use this approach based on how we’ve defined Book. Why that is will be answered in a following assignment.
A Few More Tests
Here are a few more tests to verify basic functionality. These also belong in LibraryTest.java.
Summary: Inheritance
That’s pretty much it. If we had started with a base class called Resource, this work would have been trivial. Adding new subclasses is quite easy. Figuring out which representation may take a little experimentation, but it’s easy to change.
Queries are inherently polymorphic in nature if that makes sense for the given query. Your challenge is working with a base type insead of down-casting to a derived type.
Comments