Encapsulation: private Fields and Methods

Hide an object's data behind methods so it can never be put into a bad state, like a negative deposit.

Java · beginner · 7 min · 14 steps · free

What you'll learn

EncapsulationDemo.java

class BankAccount {
    private double balance;

    double getBalance() {
        return balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}

public class EncapsulationDemo {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.deposit(50);
        acc.deposit(-20);
        System.out.println(acc.getBalance());
    }
}

Step by step

  1. Java runs the BankAccount constructor to set up the new object. The program starts in main. args holds its command-line arguments (none here).
  2. BankAccount() has finished, so its variables are gone.
  3. acc is created on the stack and points to a new BankAccount on the heap: {balance: 0}.
  4. Java calls deposit(), with amount = 50. It gets its own variables on the stack.
  5. 50 > 0: a valid deposit.
  6. balance in the BankAccount that acc points to changes from 0 to 50.
  7. deposit() has finished, so its variables are gone.
  8. Java calls deposit(), with amount = -20. It gets its own variables on the stack.
  9. -20 fails the check.
  10. deposit() has finished, so its variables are gone.
  11. Java calls getBalance(). It gets its own variables on the stack.
  12. getBalance() has finished, so its variables are gone.
  13. It prints 50.0.
  14. Balance 50.0: the bad deposit was refused because the only way in was through deposit's check.

Common mistakes

Best practices

Key takeaways

Check yourself

Which keyword hides a field?

Answer: private. private limits access to the class.

Why use getters instead of public fields?

Answer: The class keeps control of its data. You can add rules later without changing callers.

·

More in Object-Oriented Programming