Chapter 05Part II · Objects
Constructors, static and Initializer Blocks
In this chapter: how an object comes to life, in what order Java runs your initialization code, what
staticreally means, and the Java 25 change that finally lets constructors do work before callingsuper().
Key points
- A constructor initializes a new object. If you write none, the compiler adds a no-argument one.
- Order: static blocks run once when the class initializes; then, for each object, instance initializers run, then the constructor body.
this(...)calls another constructor of the same class;super(...)calls the parent's. Until Java 25 one of them had to be the very first statement.staticmembers belong to the class, shared by all objects. Static methods have nothis.- Since Java 7, a class needs a
mainto be launched; its static block no longer runs first. - Java 25 (flexible constructor bodies): you can validate and prepare arguments before
super(...).
Constructors
A constructor looks like a method with the class's name and no return type. It runs exactly once per object, right after memory is allocated and fields are set to their defaults.
In the Java 7 era, two styles were usually distinguished:
- A default (no-argument) constructor gives every object the same starting values.
- A parameterized constructor gives each object its own values.
The classic rule
"Rule → If there is no constructor in a class then the non-parameterized constructor is in-built. The compiler adds it at compilation."
True, with one consequence that surprises people: as soon as you write any constructor, the compiler stops adding the no-argument one.
Constructor chaining with this(...)
public class Chaining {
final String name;
final int age;
Chaining() {
this("unknown"); // must be the first statement (before Java 25)
System.out.println(" no-arg constructor");
}
Chaining(String name) {
this(name, 0);
System.out.println(" one-arg constructor");
}
// the one constructor that does the real work
Chaining(String name, int age) {
this.name = name;
this.age = age;
System.out.println(" two-arg constructor");
}
public static void main(String[] args) {
Chaining c = new Chaining();
System.out.println(c.name + ", " + c.age);
}
}
Each constructor delegates to a more complete one, so the real initialization lives in one place. The output runs "backwards" because each this(...) call finishes before the rest of the calling constructor runs.
The classic rule
"Rule → During constructor chaining, always keep one constructor which does not call this(), otherwise recursion will occur."
The compiler enforces this today: a cycle of this(...) calls is a compile error ("recursive constructor invocation").
Initialization order
public class InitOrder {
static int created;
static { // runs once, when the class is initialized
System.out.println("1. static block");
}
{ // runs for every object, before the constructor body
created++;
System.out.println("2. instance initializer (object #"
+ created + ")");
}
InitOrder() {
System.out.println("3. constructor");
}
public static void main(String[] args) {
System.out.println("main starts");
new InitOrder();
new InitOrder();
System.out.println("objects created: " + InitOrder.created);
}
}
1. static block
main starts
2. instance initializer (object #1)
3. constructor
2. instance initializer (object #2)
3. constructor
objects created: 2
flowchart TD
L["Class is loaded"] --> S["Static initializers run once<br/>(static fields, static blocks, in source order)"]
S --> N["new InitOrder()"]
N --> A["Memory allocated,<br/>fields set to defaults"]
A --> SUP["super(...) runs<br/>(the parent class is built first)"]
SUP --> I["Instance initializers run<br/>(field initializers, { } blocks, in source order)"]
I --> C["Rest of the constructor body"]
C -->|"next new"| N
Notice that the static block printed before main starts. The class had to be initialized before the JVM could call its static main.
- A static block (
static { … }) runs once, when the class is first initialized. Use it for setup that needs more than a one-line field initializer, such as filling a lookup table. - An instance initializer (
{ … }) runs for every object, before the constructor body. It's rarely needed in practice, but it's handy in anonymous classes, which can't declare constructors (Chapter 10).
static: belonging to the class
public class StaticRules {
static int instances; // one copy, shared by every object
int id; // one copy per object
StaticRules() { id = ++instances; }
static String describe() {
// would not compile: no 'this' in a static method
// return "id " + id;
return instances + " instances so far";
}
public static void main(String[] args) {
StaticRules a = new StaticRules();
StaticRules b = new StaticRules();
System.out.println("a.id=" + a.id + " b.id=" + b.id);
System.out.println(StaticRules.describe());
}
}
A static field exists once per class, no matter how many objects there are. A static method runs without an object, so it has no this and can't touch instance fields directly.
The classic rule
"Rule → Always keep those properties of an object as static data members whose values are same for each object. Keep those behaviours as static functions which are not performing a task for a particular object."
Good guidance that holds up. Two modern refinements: shared mutable static state is a common source of bugs in multithreaded code (Chapter 18), and static fields should usually be final constants.
Running code without main
Here's a famous old trick, and the fact that Java 7 killed it:
The classic rule
"IQ) Can we execute any code of a program without executing main()? → Yes, but after JDK 1.7, NO."
In Java 6, running a class with only a static block printed the block's output, then complained about the missing main. Since Java 7, the launcher checks for main before initializing the class:
class NoMain {
static {
System.out.println("static work"); // Java 6: printed, then an error
}
}
Error: Main method not found in class NoMain, please define the main method as:
static block lines printed: 0
The static block never runs. (This book's test for it covers Java 7–24. Java 25's launcher accepts more main shapes, so its error text may differ, but a class with no main at all is still refused.)
Work before super(): Java 25
For almost thirty years, super(...) or this(...) had to be the first statement of a constructor. That made a simple task awkward: checking or transforming an argument before passing it to the parent.
The old workaround hid the logic in a static helper:
public class ValidateBeforeSuper7 {
static class Account {
Account(String id) { System.out.println("Account " + id); }
}
static class Savings extends Account {
Savings(String id) {
// before Java 25: work hides in a static helper
super(normalize(id));
}
private static String normalize(String id) {
if (id.isBlank()) throw new IllegalArgumentException("empty id");
return id.strip().toUpperCase();
}
}
public static void main(String[] args) {
new Savings(" sb-01 ");
try {
new Savings(" ");
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
Java 25 finalized flexible constructor bodies (JEP 513). Statements may now come before super(...), as long as they don't use the object being built (no reading its fields or calling its instance methods):
public class ValidateBeforeSuper25 {
static class Account {
Account(String id) { System.out.println("Account " + id); }
}
static class Savings extends Account {
Savings(String id) {
// Java 25:
if (id.isBlank()) throw new IllegalArgumentException("empty id");
// statements
String clean = id.strip().toUpperCase();
// before super()
super(clean);
}
}
public static void main(String[] args) {
new Savings(" sb-01 ");
try {
new Savings(" ");
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
Same behavior, written the obvious way. The part before super(...) is called the constructor's prologue. It can also assign the class's own fields before calling super(...), which closes a long-standing hole where a parent constructor could call an overridden method and see the child's fields still unset.
The classic rule
"Rule → Whenever we are achieving constructor chaining using this() / this(args), then it must be the first statement."
True from Java 1.0 to Java 24. Since Java 25, it must be the first statement that touches this; validation can come before it.
Go deeper in the complete edition
This page is the focused edition. The complete edition of this chapter on GitHub adds the deep dives, puzzles, exercises and interview questions, with every sample ready to run.
Summary
- Constructors initialize objects; the compiler adds a no-argument one only if you write none.
- Order: static initializers once; then per object,
super(...), instance initializers, constructor body. staticmembers belong to the class. Static methods have nothis.- Since Java 7, no
mainmeans the class isn't launched at all. - Java 25 lets constructors validate and prepare arguments before
super(...).
Next: Chapter 6 looks at methods: overloading rules, how arguments are passed, and how Java decides which method actually runs.