Course outline · 0% complete

0/29 lessons0%

Course overview →

Encapsulation: private, getters, toString

lesson 5-3 · ~6 min · 15/29

Guarding your fields

In lesson 5-1, anyone could write rex.age = -50. In a program with one file that is survivable; in a codebase where 40 other classes touch your BankAccount, one careless write from anywhere corrupts data that every other feature trusts. Encapsulation closes that door: mark fields private so only code inside the class can touch them, then expose controlled access through methods.

class BankAccount {
  private int balance = 0;

  void deposit(int amount) {
    if (amount > 0) {
      balance += amount;
    } else {
      System.out.println("deposit rejected");
    }
  }

  int getBalance() {
    return balance;
  }
}

Now every change to balance passes through deposit, which enforces the rules. A method that reads a field is a getter (getBalance), one that writes it with validation is a setter (setName). Outside code writing account.balance = 999 no longer compiles.

Code exercise · java

Run this. The invalid deposit is rejected by the class itself, so the balance stays correct. Also note println(account): Java calls the object's toString() method to decide what to print.

toString and access levels

toString() is Java's __str__: override it and printing an object shows something readable instead of BankAccount@1b6d3586. The @Override annotation asks the compiler to verify you really are replacing an inherited method, catching typos like tostring.

One more term before the access table makes sense: a package is Java's way of grouping related classes under a shared name, the way folders group files — each class declares its package at the top of the file (package com.shop.billing;), and classes in the same package sit in the same folder of the project. The standard library ships packages like java.util, where its collections live — that is what an import java.util.ArrayList; line refers to, and you will lean on it heavily soon (unit 7 puts it to work).

The access keywords you now know:

KeywordWho can access
publicany code anywhere
privateonly inside the same class
(none)any code in the same package — the default when you write no keyword

House style for classes: fields private, methods public unless they are internal helpers. This keeps every object in charge of its own valid state, the core promise of OOP.

Quiz

A field is declared private int balance. What happens when code in another class writes account.balance = 999?

Code exercise · java

Your turn. Build a Player class: private String name, private int score starting at 0. The constructor takes the name. addPoints(int p) increases score only when p is positive. Add getName() and getScore(), and a toString() returning `<name>: <score>`. Main should print `Ada: 15`.