Objects that hold their shape · chapter 11 of 33
Encapsulation: deciding who can change your data
Chapter 2.1 · Part 2, Objects that hold their shape · about 30 minutes
What you need before this chapter: everything in Part 1, through chapter 1.10, enum and record. That means classes, objects, fields, constructors, private, and null. It also means references and interfaces. Inheritance and exceptions round out the list.
When you finish this chapter you will be able to:
- Explain, with a concrete example, why a field that any code can set is a source of bugs and not only a style complaint
- Turn a class with public fields into one where every state change goes through a method that can refuse it
- Recognise "fake encapsulation": a private field with a getter and a setter that do nothing, and say why it fixes nothing
- Say what
privateactually guarantees in Java, and what it does not
1. Where chapter 1.1 left off
Chapter 1.1 built a Ticket with two public fields. It warned that this was a real flaw: any code, anywhere, could reach into a ticket and change its plate or its arrival time to nonsense. This chapter is where that gets fixed. The fix is worth building slowly, because the wrong version of it is everywhere in real code.
Start by extending the ticket from 1.1 with two more fields a parking lot actually needs: whether the ticket has been paid, and the minute the vehicle left.