×

java · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.