Demo: modernizing a legacy Java class step by step
On This Lesson 3 topics
The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.
In this lesson
turn an old getter/setter class into modern Java. Prepares JNR-001-LAB1.
Draft outline details
Step by step
- Show the legacy
Productclass: fields, getters, setters,equals,hashCode,toString. - Run the existing tests so you have a safety net.
- Replace the class with a record; remove the setters and fix the callers.
- Planned mistake: the class had a
List<String> tags. Passing a list that the caller changes later breaks immutability. Fix: copy it in the compact constructor withList.copyOf. - Replace the
if/else instanceofchain with a sealed interface and a switch. - Run the tests again and list what you removed.
Check your understanding
Why copy the list?
Show answer
A record is shallow; a shared list can still be changed from outside.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.