Command Palette

Search for a command to run...

Back to the lesson: Topic 4.5 — Encapsulation and Access Modifiers
Core Java · Example 1 of 3

An account that can't be put in a bad state

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.

01

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.

02

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.

03

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

01

What is encapsulation, and why is it more than adding getters and setters?

02

List the four access levels from narrowest to widest and say who can use each.

03

Why can one Account method read the private balance of a different Account object?

04

What is a leaky getter, and how do you fix it?

An account that can't be put in a bad state
Sign in to run this example in your browser.

Expected output

withdraw 1000: false
withdraw 300:  true
Asha balance: 450
deposit -50 rejected: amount must be > 0
new account rejected: opening balance -1 < 0
Asha richer than Ben? false