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.
getX
x
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.
getBalance()
balance
setBalance
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?