Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Class or type (20 minutes)
For List<String> a = new ArrayList<>(); say the declared type and the class of the object.
Done when: two answers and a sentence on why they differ.
Hint
The declared type is on the left, and the class is after new.
Easy 2: Spot the concrete dependency (20 minutes)
Find three variables or parameters in code you have written that name a concrete class where an interface would do.
Done when: three lines with the interface that could replace each.
Hint
Look at fields, parameters and return types.
Easy 3: Name the role (20 minutes)
Write interface names and one method each for: sending a message, picking a price, telling the time, storing a file.
Done when: four interfaces.
Hint
Name the role, not the technology.
Medium
Medium 1: Add a payment method (30 minutes)
Compile the PaymentMethod example. Add BankTransfer without changing Checkout.
Done when: a running program with three methods used by one Checkout.
Hint
Add a class that implements the interface and pass it in.
Medium 2: Clock (30 minutes)
Write a Clock interface with long now(), a real implementation and a fixed one for tests. Use it in a class that checks whether a booking is in the past.
Done when: a test that passes with the fixed clock.
Hint
The fixed clock returns whatever number the test sets.
Medium 3: Mixin (30 minutes)
Make a Room class that implements Comparable<Room> by capacity. Sort a list of rooms.
Done when: sorted output and one sentence on what the mixin added.
Hint
Compare capacities with Integer.compare.
Hard
Hard 1: Interface or abstract (45 minutes)
Design Vehicle, Car and Bike with a shared plate number. Do it once with an abstract class and once with an interface plus a small helper class. Compare.
Done when: two versions and a half-page comparison.
Hint
An abstract class can hold the plate number directly.
Hard 2: Too many methods (45 minutes)
Take a Printer interface with eight methods. Split it into smaller interfaces and show a class that needs only one of them.
Done when: a new set of interfaces and the class that uses one.
Hint
Group methods by who calls them.
Hard 3: Evolving an interface (50 minutes)
A published interface needs a new method. Show how a default method avoids breaking existing classes, and what risk remains, using EJ's caution.
Done when: code, plus a paragraph on the risk.
Hint
A default method gives old classes a body, but the body may not suit them.