Command Palette

Search for a command to run...

Back to the lesson: Topic 4.2 — Fields and Instance Methods
Core Java · Example 2 of 3

Queries vs commands on a rectangle

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.

01

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().

02

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.

03

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

01

What is the difference between an instance field and a local variable, in terms of where it lives and how long it lives?

02

How can one copy of a method's bytecode work correctly for thousands of different objects?

03

Why does main get a compile error when it calls an instance method of Main directly?

04

In what order do field initialisers run, and what's the danger of a field initialiser calling a method?

Queries vs commands on a rectangle
Sign in to run this example in your browser.

Expected output

area:      12
perimeter: 14
square?    false
after scale(2): 8 x 6
area:      48
area again 48