Java 6: Classes, Constructors & this/super
easy⏱ 5 mincoursejava
Construction order
On new Child(): (1) static blocks of Parent and Child run once on class load, top-to-bottom. (2) Parent instance initializers + Parent constructor body run. (3) Child instance initializers + Child constructor body run. Missing this order is how people break subclassing — e.g., a Parent constructor calling an overridden method sees Child fields still at defaults.
class Parent {
int x = log("parent field", 1);
Parent() { log("parent ctor", 0); }
int log(String msg, int v) { System.out.println(msg); return v; }
}
class Child extends Parent {
int y = log("child field", 2);
Child() { log("child ctor", 0); }
}
// new Child() prints: parent field, parent ctor, child field, child ctor
this() and super() rules
Either this(args) or super(args) — never both — and it must be the first statement in a constructor. If you write neither, the compiler inserts super() (zero-arg parent). If the parent has no zero-arg constructor, you must call a specific super(args) explicitly or the child won't compile.
Build an init-order tracer
Simulate Parent and Child classes with static init blocks, instance field initializers, and constructors. Use a shared log: string[] array. After new Child(), the log should contain the 4-step order exactly. Then create a second Child — static blocks should not fire again.
Never call overridable methods from a constructor
If Parent's constructor calls this.format() and Child overrides format(), the Child version runs before Child's constructor has initialized its fields — they're still at default values (0/null/false). This is one of the sharpest traps in Java. Rule: constructors should only call final, private, or static methods.
Quiz: Default constructor
When does the compiler NOT insert a default constructor? When you define any constructor yourself. As soon as you write public Foo(int x) {...}, there is no more zero-arg constructor unless you add one explicitly. This breaks frameworks like JPA that require a no-arg constructor.