Part 7 of 7 · 2 min read
Exercises
Easy
Easy 1: Run Shape (20 minutes)
Compile Shape, Circle and Rectangle. Put three shapes in a list and print the total area.
Done when: a printed total and no instanceof in the code.
Hint
Loop over List<Shape> and add area().
Easy 2: Spot the tag (20 minutes)
Find three tagged classes or if chains on a type in any code you know. Name the interface you would extract.
Done when: three names with the methods.
Hint
Look for a string or enum compared in several places.
Easy 3: Override or overload (20 minutes)
Classify as overriding or overloading: two print methods with an int and a String; toString in Room; area in Circle.
Done when: three answers.
Hint
Overloading shares a name and differs in parameters.
Medium
Medium 1: Fee policies (30 minutes)
Compile the FeePolicy classes. Add StudentFee with 25 percent off, and print fees for a base of 2,000 cents.
Done when: four printed fees: 0, 2000, 1000 and 1500.
Hint
2,000 times 0.75 is 1,500.
Medium 2: Convert a tagged class (30 minutes)
Convert the EJ Figure into a hierarchy yourself, with a third flavour, a triangle.
Done when: a root type, three subclasses and a test of each area.
Hint
Move each case into the matching class.
Medium 3: Catch the typo (30 minutes)
Write a subclass method with a slightly wrong signature. Show that without @Override it compiles and misbehaves, and that with @Override the compiler stops it.
Done when: two compiler runs with their results.
Hint
Change a parameter type by one letter.
Hard
Hard 1: Notification kinds (45 minutes)
Start from a Notification class with a type string and if chains in send and cost. Replace it by a hierarchy for email, SMS and push.
Done when: before and after code with the same output.
Hint
Each type gets its own send and cost.
Hard 2: A broken promise (45 minutes)
Write an implementation of Shape that returns a negative area. Write a test that finds it, and write the interface comment that would have prevented it.
Done when: a failing test and a documented interface.
Hint
Check that no area is below zero.
Hard 3: Cost of a new kind (50 minutes)
For a design with 6 methods and 4 kinds, count the edits to add a fifth kind in the tagged version and in the hierarchy version. Then name one situation where the tagged version is cheaper.
Done when: two counts and a paragraph.
Hint
One kind with many unrelated methods can be simpler as a switch.