A bank account with its own rules
Fields are an object's memory: the data it carries between method calls. Instance methods are the object's behaviour: code that reads and changes that object's own fields, so the data and the rules for it live together.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Thermostat with a double target field and methods up() (adds 0.5), down() (subtracts 0.5) and describe() (returns "Target: <target>"). Start at 20.0, call up() three times and down() once, and print describe().
Write a class Player with String name and int score, a command addPoints(int p) that ignores negative values, and a query isWinning(Player other). Show it with two players.
Write a class Stopwatch with an int laps field and a method lap() that returns the new lap number. Call it three times and print each return value.
Explain it without notes
What is the difference between an instance field and a local variable, in terms of where it lives and how long it lives?
How can one copy of a method's bytecode work correctly for thousands of different objects?
Why does main get a compile error when it calls an instance method of Main directly?
In what order do field initialisers run, and what's the danger of a field initialiser calling a method?
Expected output
withdraw 300: true
withdraw 900: false
transfer 200: true
Asha has 500 after 3 transactions
Ben has 200 after 1 transactions