Java · Beginner level

Beginner level · Module 4: Classes and Objects in Java · Lesson 3 of 3

Encapsulation: Protecting an Object's Data

Make fields private and control changes through methods that check the rules, so objects can never hold invalid data.

In this lesson you will

  • Use private fields with getters and validating methods
  • Throw IllegalArgumentException for invalid values

Key concepts

privategetter and settervalidationinvariant

The lesson

Encapsulation means hiding an object's fields and allowing changes only through methods. With private double balance, no other class can set the balance to -5,000; it must call deposit() or withdraw(), which check the amount first.

A getter such as getBalance() lets other code read a value. Only add a setter if outside code genuinely needs to change that value, and validate inside it. Many fields should never have a setter at all.

When a method receives an invalid value, signal it clearly: throw new IllegalArgumentException("Amount must be positive");. The program stops with that message unless the caller handles it, which is far safer than silently storing wrong data.

Step by step

  1. Make the fields of BankAccount private.
  2. Add getBalance() and remove any setter for balance.
  3. Write deposit() and withdraw() that reject non-positive amounts and overdrafts.
  4. Test valid and invalid operations from main.

Practice activity

Complete a MobileWallet class with deposit, withdraw and transfer methods that never allow a negative balance, and test every rule.

Expected result: Valid transactions update the balance; invalid ones throw an exception with a clear message and leave the balance unchanged.

Check your understanding

  1. Why make fields private?

    Show answer

    So that only the class's own methods can change them, keeping the data valid.

  2. What should withdraw() do if the amount exceeds the balance?

    Show answer

    Reject it, for example by throwing an exception, and leave the balance unchanged.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.