← Back to course

Encapsulation

You’ll be able to

Hiding the data

Encapsulation means keeping an object’s data private and exposing only controlled access through public methods. A private field cannot be read or written directly from outside its class. This lets the class guard its own invariants — for example, a bank account can reject a negative deposit — instead of trusting every outsider to modify the data correctly.

Public methods as the interface

The public methods form the object’s interface to the outside world. A getter such as getBalance() returns the private field; a mutator such as deposit(double amt) updates it under the class’s own rules (balance += amt). Outside code goes through these methods and never touches the field directly, so the class stays in control of its state.

Private means private

Because a private field is invisible outside its class, a statement like a.balance = 200.0; written in another class fails to compile. Calling a public method that happens to touch the field, like a.getBalance() or a.deposit(20.0), is fine. The compiler enforces the boundary — encapsulation is not a suggestion.

Encapsulation pattern
private field + public getter/setter = controlled access
Data is hidden; all reads and writes flow through methods the class controls.
Worked example

Given class Account { private double balance = 100.0; public void deposit(double amt) { balance += amt; } public double getBalance() { return balance; } }, trace: Account a = new Account(); then a.deposit(50.0); then System.out.println(a.getBalance());

  1. 1.new Account() starts balance at 100.0.
  2. 2.a.deposit(50.0) runs balance += amt, so balance becomes 100.0 + 50.0 = 150.0.
  3. 3.a.getBalance() returns the current balance, 150.0.
Answer: It prints 150.0 — the starting 100.0 plus the 50.0 deposit.
Checkpoint

Given `class Account { private double balance = 100.0; public void deposit(double amt) { balance += amt; } public double getBalance() { return balance; } }`, what does this print? `Account a = new Account();` then `a.deposit(50.0);` then `System.out.println(a.getBalance());`

Tip

Encapsulation is why classes expose getters and setters instead of public fields: the methods can validate input and keep the object’s data consistent.

Checkpoint

For the same `Account` class (with `private double balance`), and `Account a = new Account();` written in a *different* class, which statement causes a compile error?

On the exam

On the exam, directly reading or writing a private field from outside its class is always an error. Legal access outside the class must go through a public method.

Answer the 2 checkpoints as you read.

Sign in to save your progress