Learn Java · lesson 40 of 61 · about 8 minutes
Encapsulation
Take payment by gift card: hide fields with private, and expose safe getters and methods that protect the object's rules.
What you'll learn
- Make fields private
- Write getters and validated setters
- Use final for values that never change
The gift card
Every customer tonight gets a $20 gift card with a code made from their name, like GC-ADA. The code never changes, so it's a final field. The balance must never go below 0 or be changed by the rest of the program, so it's private: the only way to spend it is pay(cents), which refuses amounts that aren't above 0 or are more than the balance, and says whether it worked. getCode() and getBalance() let the desk read both.
Protect the rules
If any code can write account.balance = -1000;, the class can't keep its promises. So:
- fields are
private getX()methods read them- methods that change them check the rules first
finalfields can only be set once, in the constructor
What goes wrong without them
class Account {
int balance = 0;
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.balance = -1000;
System.out.println(a.balance);
}
}
Output
-1000The rules
A private field with a setter that checks its value can never hold a bad one. The constructor can use the same setter, so the rule is written once.
A thermostat that stays in range
class Thermostat {
private int temp;
Thermostat(int temp) {
setTemp(temp);
}
int getTemp() {
return temp;
}
void setTemp(int t) {
this.temp = Math.max(10, Math.min(30, t));
}
}
public class Main {
public static void main(String[] args) {
Thermostat t = new Thermostat(45);
System.out.println(t.getTemp());
t.setTemp(5);
System.out.println(t.getTemp());
}
}Output
30
10Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.