Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.4 Encapsulation — getters

Lesson

Reading a private field: the getter

A getter is a method that returns the value of a private field, giving the outside world read access without exposing the field itself. By convention it is named getX for a field x and simply returns it.


Worked example

class Account {
    private int balance;

    int getBalance() {
        return balance;      // read access to the private field
    }
    void setBalance(int b) {
        balance = b;
    }
}

Account a = new Account();
a.setBalance(100);
System.out.println(a.getBalance());   // 100

▶ Try it: getBalance() returns the private balance. Run this, then change the amount passed to setBalance and re-run.



What is a getter?


getBalance() returns the private balance. How do you read it from outside the class?


Type exactly what this program prints.

class Account {
    private int balance;

    int getBalance() {
        return balance;
    }

    void setBalance(int b) {
        balance = b;
    }
}

public class Main {
    public static void main(String[] args) {
        Account a = new Account();
        a.setBalance(100);
        System.out.println(a.getBalance());
    }
}

True or false?