A temperature with a validating setter
Encapsulation means an object hides its data and lets the outside world change it only through methods that enforce the rules. Java's access modifiers (private, package-private, protected, public) decide exactly which code can see each class, field, method and constructor.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Counter with a private int count, a public increment(), a public getCount(), and a public reset(). Show that main can use the methods but not the field.
Write a class Password that stores a private String value, accepts it in the constructor only if it has at least 8 characters, and exposes matches(String attempt) but no getter. Show one accepted and one rejected password.
Write a class Playlist with a private String[] songs that copies the array in the constructor and returns a copy from getSongs(). Prove that changing the returned array doesn't change the playlist.
Explain it without notes
What is encapsulation, and why is it more than adding getters and setters?
List the four access levels from narrowest to widest and say who can use each.
Why can one Account method read the private balance of a different Account object?
What is a leaky getter, and how do you fix it?
Expected output
start: 21.0
set 23.5: 23.5
set 80 rejected: 80.0 not in [10.0, 30.0]
still: 23.5