java · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A setter with a rule. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Player {
private int lives;
int getLives() { return lives; }
void setLives(int lives) {
if (lives >= 0 && lives <= 5) {
this.lives = lives;
}
}
}
public static void main(String[] args) {
Player player = new Player();
player.setLives(3);
player.setLives(9);
player.setLives(-1);
System.out.println("Lives: " + player.getLives());
}
}
your turn
Your turn. Guard the thermostat.
Fill in the rule on line 6 so only temperatures from 10 to 30 get in. Pick any temperature on line 14, then press run. The 45 on line 15 should bounce off.
output
press run to see what happens
fix it
The bank lets you take out too much. Fix it!
output
press run to see what happens
- The balance drops below 0. Does anything in
withdrawcheck whether there is enough money? - Wrap line 7 in an
if, so the money only leaves whenamount <= balance. - Put
if (amount <= balance) {before line 7 and a}after it, then press run.
nailed it
your objects guard their own fields. :D
privatefields are for their own class only.- Getters read fields, and setters can refuse bad values.
- Encapsulation keeps every object's values sensible.
new words in your collection
- private
- encapsulation
- getter
- setter
This lesson isn’t saved. A free account remembers every lesson you finish.