×

java · level 2 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Make fields and offer safe methods instead.

If any code can write account.balance = -500;, your bank is in trouble. Mark the field private, for its own class only, and offer methods instead. This idea is called : each object guards its own fields.

A , like getBalance(), hands a value back. A , or a method like payIn, changes it, and can refuse nonsense first, such as paying in a negative amount.

One quirk: our classes sit inside Main, so Java lets Main peek at their private fields. In bigger projects each class has its own file, and Java blocks the peek. Use the methods anyway.

public class Main {
    static class Account {
        private int balance;
        int getBalance() {
            return balance;
        }
        void payIn(int amount) {
            if (amount > 0) {
                balance = balance + amount;
            }
        }
    }
    public static void main(String[] args) {
        Account account = new Account();
        account.payIn(50);
        account.payIn(-500);
        System.out.println("Balance: " + account.getBalance());
    }
}

Getter names start with get and setter names with set, followed by the field name.