Watch the construction order
Initialisers ran once per object, even through the this(...) chain.
A constructor is the special block that runs once when an object is created with new, so the object starts life complete and valid. Constructors can be overloaded and can call each other with this(...), keeping the setup logic in one place.
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 Temperature with a double celsius field and two constructors: Temperature(double celsius) and Temperature() which chains to 20.0. Reject values below -273.15 with IllegalArgumentException. Print two temperatures and a rejected one.
Write a class Rect with constructors Rect(int w, int h) and Rect(int side) (a square, chaining to the first) and a method area(). Print the area of a 3x5 rectangle and a 4x4 square.
Write a class Counter with an instance initialiser block that prints init block, a field initialiser int start = 10; and a constructor that prints constructor, start = <start>. Create two counters and show the output.
Explain it without notes
What is a constructor, and how is it different from a method?
When does the compiler generate a default constructor, and when doesn't it?
Describe the full order of events in new Widget("w1") for a class with field initialisers and an instance initialiser block.
Why must this(...) be the first statement of a constructor, and what changed in Java 25?
Why is a constructor a good place to validate input?
Expected output
-- new Widget("w1")
field a initialiser
instance initialiser block
field b initialiser
Widget(String) body, name = w1
-- new Widget()
field a initialiser
instance initialiser block
field b initialiser
Widget(String) body, name = default
Widget() body, after this(...)