Sub topic 15
Pitfall: Calling Overridable Methods from Constructors
In earlier chapters you saw that Java picks an overridden method based on the object's runtime type. That rule has a strange side effect. It still applies while an object is being built. This chapter shows why that can cause bugs, and how to avoid them.
A constructor is the special block of code that runs when you create an object with new. An overridable method is any method a subclass can replace. In Java, that means any method that is not private, static, or final.
The Surprise
Look at this program. Base calls init() from its constructor. Derived overrides init() and uses one of its own fields.
class Base {
Base() {
System.out.println("Base constructor starts");
init();
System.out.println("Base constructor ends");
}
void init() {
System.out.println("Base.init");
}
}
class Derived extends Base {
private String message = "ready";
Derived() {
System.out.println("Derived constructor body: " + message);
}
@Override
void init() {
System.out.println("Derived.init: " + message);
}
}
public class Main {
public static void main(String[] args) {
new Derived();
}
}Save this as Main.java, then compile and run it with javac Main.java and java Main. The output is:
Base constructor starts
Derived.init: null
Base constructor ends
Derived constructor body: readyThe second line is the problem. The field message is set to "ready" in its declaration, but Derived.init() printed null. The rest of this chapter explains why.
Why It Happens: The Order of Construction
When you write new Derived(), Java builds the object in a fixed order:
- Java sets aside memory for the whole object. Every field starts at its default value, the value a field has before any code sets it. Object references start as
null, numbers as0, and booleans asfalse. - The
Derivedconstructor starts. Its first step is always a call to the superclass constructor. If you don't writesuper(), Java adds it for you. - The
Baseconstructor runs. It callsinit(). - The object is already a
Derived, so dynamic dispatch runsDerived.init(). Dynamic dispatch is the runtime choice of method that you learned about earlier. Derived.init()readsmessage. The field initializer formessagehas not run yet, so the value is stillnull.- The
Baseconstructor finishes. - Back in
Derived, the field initializers run, andmessagebecomes"ready". - The body of the
Derivedconstructor runs.
A field initializer is the = "ready" part of a field declaration. It runs only after the superclass constructor has returned.
In short, the superclass calls into subclass code before the subclass part of the object has been set up.
What the Overridden Method Sees
While the superclass constructor is running, every field declared in the subclass still holds its default value.
| Field type in subclass | Value seen during superclass constructor |
|---|---|
| `String`, arrays, or any object type | `null` |
| `int`, `long`, `short`, `byte` | `0` |
| `double`, `float` | `0.0` |
| `boolean` | `false` |
| `char` | `'\u0000'` (the zero character) |
Printing null is a mild problem. Wrong numbers are worse because they look normal. Crashes are also common.
When It Crashes
Here the overridden method calls a method on a field that is still null:
class Widget {
Widget() {
System.out.println("Label length: " + labelLength());
}
int labelLength() {
return 0;
}
}
class Button extends Widget {
private String label = "OK";
@Override
int labelLength() {
return label.length();
}
}
public class Main {
public static void main(String[] args) {
new Button();
}
}Running this throws a NullPointerException inside Button.labelLength(). The stack trace points at Button, but the cause is in Widget's constructor. That makes this bug hard to track down.
Edge Case: final Fields Do Not Save You
You might think a final field set in the constructor would be safe. It is not. The constructor body that assigns the field runs after super() returns.
class Base {
Base() {
show();
}
void show() {
}
}
class Derived extends Base {
private final String name;
Derived(String name) {
super();
this.name = name;
}
@Override
void show() {
System.out.println("name = " + name);
}
}
public class Main {
public static void main(String[] args) {
new Derived("Ada"); // prints "name = null"
}
}Java promises that a final field is assigned exactly once. It does not stop other code from reading the field before that assignment happens.
How to Avoid the Pitfall
The rule is simple: a constructor should only call methods that subclasses cannot override. Here are three ways to follow it.
Fix 1: Make the Helper Method private or final
A private method is not inherited, so dynamic dispatch never applies to it. A final method cannot be overridden. Either one guarantees the constructor runs the code you wrote.
class Base {
private int setupCount;
Base() {
setUp();
}
private void setUp() {
setupCount = 1;
System.out.println("Base set up, count = " + setupCount);
}
}
class Derived extends Base {
// Derived cannot override setUp(), so Base() always runs Base's version.
}
public class Main {
public static void main(String[] args) {
new Derived(); // prints "Base set up, count = 1"
}
}Fix 2: Pass Values Up Instead of Calling Down
Sometimes the superclass needs information that only the subclass has. Don't get it through an overridden method. Have the subclass pass it to the superclass constructor as an argument.
class Widget {
private final String label;
Widget(String label) {
this.label = label;
System.out.println("Label length: " + label.length());
}
}
class Button extends Widget {
Button() {
super("OK");
}
}
public class Main {
public static void main(String[] args) {
new Button(); // prints "Label length: 2"
}
}The value reaches the superclass before it is used, so nothing is null.
Fix 3: Do the Extra Work After Construction
If a step really must be overridable, run it after the object is fully built. A static factory method works well for this. It is a static method that creates the object, finishes setting it up, and returns it.
class Report {
private final String title;
private Report(String title) {
this.title = title;
}
static Report create(String title) {
Report r = new Report(title);
r.start(); // the constructor has finished, so every field is set
return r;
}
void start() {
System.out.println("Starting report: " + title);
}
}
public class Main {
public static void main(String[] args) {
Report.create("Sales"); // prints "Starting report: Sales"
}
}Quick Checklist
- Read your constructor. List every method it calls.
- Check each one. Is it
private,final, orstatic? If not, a subclass could override it. - Look for indirect calls too. A
privatehelper that calls an overridable method has the same problem. - If the class is meant to be extended, document any overridable method it calls during construction, or better, remove the call.
Exercise
What does this program print? class A { A() { print(); } void print() { System.out.println("A"); } } class B extends A { int x = 5; @Override void print() { System.out.println("B " + x); } } and main runs new B();
Show answer
It prints "B 0". The A constructor runs before B's field initializers, and dynamic dispatch calls B.print(). The int field x still has its default value 0.
Exercise
A class Vehicle calls wheelCount() from its constructor, and the subclass Bike overrides wheelCount() to return a field wheels that is set to 2. Name two ways to make Vehicle receive the correct value.
Show answer
One way is to pass the value up: give Vehicle a constructor Vehicle(int wheels) and have Bike call super(2). Another is to stop calling wheelCount() from the constructor and call it later, for example from a static factory method after the object is built. Making wheelCount() final in Vehicle also stops the bug, but then Bike can no longer override it.
Exercise
A constructor calls a private method helper(), and helper() calls a public method log() that subclasses override. Is the constructor safe?
Show answer
No. helper() itself cannot be overridden, but it calls log(), which can. The overridden log() still runs before the subclass fields are initialized. Every method reached from the constructor, directly or indirectly, must be non-overridable.