java · level 3 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An object never changes once it is built.
If any code can call setPrice on your object, every part of the program holding it can be surprised. An immutable object removes that worry. Once built, its fields never change, so you can share it freely, even with code you did not write.
The recipe: make every field , set each one in the constructor, and write no setters. final means one value, once. Assign it again and the program will not compile.
Need a change? Return a new object instead: price.plus(399) builds a fresh Money and leaves the old one alone. String works like this, which is why toUpperCase hands back a new string.
public class Main {
static class Money {
private final long pence;
private final String currency;
Money(long pence, String currency) {
this.pence = pence;
this.currency = currency;
}
Money plus(long more) {
return new Money(pence + more, currency);
}
@Override
public String toString() {
return String.format("%d.%02d %s", pence / 100, pence % 100, currency);
}
}
public static void main(String[] args) {
Money price = new Money(1250, "GBP");
Money withDelivery = price.plus(399);
System.out.println(price);
System.out.println(withDelivery);
}
} %02d pads a number to two digits with a zero, so 5 pence shows as 05.
guess first
The list is final. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.ArrayList;
import java.util.List;
public class Main {
static class Team {
private final List<String> players = new ArrayList<>();
List<String> getPlayers() {
return players;
}
}
public static void main(String[] args) {
Team team = new Team();
team.getPlayers().add("Kane");
team.getPlayers().add("Bronze");
System.out.println(team.getPlayers());
}
}
your turn
Your turn. Move a point without changing it.
The fields are final, so moveRight cannot change x. On line 10, return a new Point that is steps further right.
output
press run to see what happens
fix it
The seat upgrade will not compile. Can you fix it?
output
press run to see what happens
- Java will not assign to the
finalfieldseaton line 8. How do immutable objects change? - They never change. They hand back a new object holding the new value.
- Replace lines 8 and 9 with
return new Ticket(newSeat);, then run.
nailed it
your objects can be trusted not to change. :D
- Immutable means every field is
private final, with no setters. - To change something, return a new object.
finalfixes the reference, not what the object holds.
new words in your collection
- immutable
- final
This lesson isn’t saved. A free account remembers every lesson you finish.