Java Constructors: Default Constructor, this() and super() (OCP 21)
Java constructors for the OCP 21 exam: declaring and overloading them, when the compiler adds a default constructor, private constructors, chaining with this(), calling the parent with super(), the inserted super() call and its traps, and Java 25 flexible constructor bodies.
kvi5hnuCode Sprout team member8 min readOn this page
A constructor runs when an object is created with new. It sets up the object's initial state. Constructors look like methods, but they follow their own rules, and the exam tests those rules heavily, especially how constructors call each other with this() and super().
Declaring a constructor
A constructor has the same name as the class (case-sensitive) and no return type, not even void:
public class Toaster {
public Toaster() { System.out.println("toast"); } // constructor
public toaster() { } // DOES NOT COMPILE: not the class name, so it's a method with no return type
public void Toaster() { } // compiles, but it's a regular METHOD named Toaster
}
The last line is a legal method that happens to share the class's name. new Toaster() doesn't call it. Only new Toaster().Toaster() would.
Other constructor rules:
- Parameters work like method parameters, including varargs, but
varisn't allowed:Bonobo(var food)doesn't compile. - The only modifiers allowed are access modifiers.
final,staticandabstractconstructors don't compile. - A bare
return;is allowed to leave early, butreturn value;isn't. - A class can have several overloaded constructors, as long as their parameter lists differ:
public class Lamp {
private String name;
public Lamp() { name = "unnamed"; }
public Lamp(int age) { }
public Lamp(long age) { }
public Lamp(String name, String... bulbs) { this.name = name; }
}
new Lamp(15) allocates memory for a new object and runs the constructor that matches the arguments, using the same resolution rules as overloaded methods (article 30).
The default constructor
Every class has at least one constructor. If you write none, the compiler adds a default constructor: it takes no parameters, has an empty body (apart from super()), and has the same access level as the class.
public class Desk1 { } // gets public Desk1() { super(); }
public class Desk2 { public Desk2() { } } // written by hand: no default added
public class Desk3 { public Desk3(boolean b) { } } // no no-arg constructor at all
public class Desk4 { private Desk4() { } } // no default added
new Desk1(); // fine
new Desk2(); // fine
new Desk3(); // DOES NOT COMPILE: constructor Desk3 cannot be applied to given types
new Desk3(true); // fine
new Desk4(); // DOES NOT COMPILE from another class: Desk4() has private access
The key rule: the compiler adds a default constructor only when the class declares no constructors at all. As soon as you write any constructor, you lose the free no-argument one.
The default constructor exists only in the compiled .class file. You won't see it in the source.
Private constructors
A class whose constructors are all private can't be instantiated by other classes, and no default constructor is added. This pattern is used for:
- utility classes with only static methods, like
java.lang.Math. They often throw anAssertionErrorin the private constructor as a safety net; - static factory methods that control how instances are created, such as
List.ofandLocalDate.of(article 23); - singletons.
Such a class also can't be extended by an ordinary top-level class, because a subclass constructor must call a parent constructor, and it can't call a private one. (A nested subclass inside the same top-level class can, because it shares private access.)
Calling another constructor with this()
Overloaded constructors often repeat the same assignments. Instead, one constructor can delegate to another with this(...):
public class Parcel {
private final int weight;
private final String color;
public Parcel(int weight, String color) {
this.weight = weight;
this.color = color;
}
public Parcel(int weight) {
this(weight, "fragile"); // calls the two-argument constructor on THIS object
}
}
Two tempting alternatives don't work:
public Parcel(int weight) {
Parcel(weight, "fragile"); // DOES NOT COMPILE: constructors can't be called by name
}
public Parcel(int weight) {
new Parcel(weight, "fragile"); // compiles, but builds a SECOND object and throws it away
}
The rules for this(), in Java 21:
- It must be the first statement in the constructor. Comments before it are fine, but no other statements.
- So a constructor can contain at most one
this()call, and it can't contain boththis()andsuper(). - Constructors can't call each other in a cycle. The compiler reports "recursive constructor invocation":
public Drill(int holes) { this(5); } // DOES NOT COMPILE: calls itself
public Drill() { this(5); }
public Drill(int holes) { this(); } // DOES NOT COMPILE: A → B → A
this (a reference to the current object) and this() (a constructor call) are unrelated features that happen to share a keyword.
Calling the parent constructor with super()
Before a subclass constructor sets up its own fields, the parent's part of the object must be initialized. The first statement of every constructor is either this(...) or super(...). If you don't write either one, the compiler inserts super();, a call to the parent's no-argument constructor.
public class Vehicle {
private final int age;
public Vehicle(int age) {
super(); // Object() — would be inserted anyway
this.age = age;
}
}
public class Bike extends Vehicle {
public Bike(int age) {
super(age); // Vehicle(int)
}
public Bike() {
this(4); // delegates; Bike(int) will call super
}
}

Following one new expression:
- Each constructor's first statement calls the next one:
this(...)within the class, orsuper(...)to the parent. - The chain always ends at
Object(). - The constructor bodies then finish in reverse order: the parent's body completes before the child's.
A subclass may call any accessible parent constructor. It doesn't need to match its own parameters:
public class Truck extends Vehicle {
public Truck(int age) { super(age); }
public Truck() { super(5); }
}
super() always refers to the direct parent. It can't skip a level to call a grandparent's constructor.
Like this(), super() must come first, and only once:
public Shelf() {
System.out.println("created");
super(); // DOES NOT COMPILE (in Java 21): not the first statement
}
public Shelf() {
super();
super(); // DOES NOT COMPILE: only one constructor call
}
The trap: a parent without a no-argument constructor
public class Machine {
public Machine(int age) { } // so Machine has NO no-argument constructor
}
public class Pump extends Machine { } // DOES NOT COMPILE
public class Crane extends Machine {
public Crane() { } // DOES NOT COMPILE
}
Neither class compiles, for the same reason. Pump gets a default constructor, Crane has a constructor without this() or super(), and in both cases the compiler inserts super();. Machine() doesn't exist, so the error is "constructor Machine in class Machine cannot be applied to given types". The fix is an explicit call:
public class Pump extends Machine {
public Pump() { super(6); }
}
public class Crane extends Machine {
public Crane() { super(4); }
}
public class TowerCrane extends Crane { } // fine: Crane() exists
When a class doesn't compile on the exam, check first whether its parent has an accessible no-argument constructor.
Constructor rules at a glance
- A constructor's name matches the class, and it has no return type.
- If no constructors are declared, the compiler adds a no-argument default constructor with the class's access level.
- The first statement is
this(...)orsuper(...). If neither is written,super();is inserted. this(...)andsuper(...)can't both appear, can't be repeated, and can't form a cycle.- If the parent has no accessible no-argument constructor, every subclass constructor must call
super(...)with arguments, directly or throughthis(...).
What's current
- Java 25's flexible constructor bodies (JEP 513) allow code before
this(...)orsuper(...)that doesn't touchthis. Java 21 forbids it, so 1Z0-830 tests the old rule. - Default-constructor rules are unchanged.
Exam traps from this article
A complete example
The program logs each constructor as its body finishes, so the trace shows the order of a chain of this() and super() calls. It also uses a default constructor and a utility class with a private constructor.
public class Solution {
static StringBuilder trace = new StringBuilder();
static void log(String step) {
trace.append(step).append(" > ");
}
// No constructor written: the compiler adds Device() { super(); }
static class Device {
String serial = "unset";
}
static class Appliance {
protected final String brand;
protected final int watts;
Appliance(String brand, int watts) { // super() to Object is inserted here
log("Appliance(String,int)");
this.brand = brand;
this.watts = watts;
}
Appliance(String brand) {
this(brand, 1000); // delegate: must be the first statement
log("Appliance(String)");
}
}
static class Kettle extends Appliance {
private final double litres;
Kettle(String brand, double litres) {
super(brand, 2200); // explicit parent constructor
log("Kettle(String,double)");
this.litres = litres;
}
Kettle(String brand) {
this(brand, 1.7); // this() first, so no super() here
log("Kettle(String)");
}
Kettle() {
this("Generic");
log("Kettle()");
}
@Override
public String toString() {
return brand + " kettle, " + watts + " W, " + litres + " L";
}
}
static class Toaster extends Appliance {
Toaster() {
super("Crisp"); // any accessible parent constructor will do
log("Toaster()");
}
@Override
public String toString() {
return brand + " toaster, " + watts + " W";
}
}
// Only a private constructor: no default constructor, and no instances from outside.
static final class Units {
private Units() {
throw new AssertionError("no instances");
}
static double kwh(int watts, double hours) {
return watts * hours / 1000;
}
}
static Object build(java.util.function.Supplier<Object> maker) {
trace.setLength(0);
Object made = maker.get();
System.out.println(made);
System.out.println(" " + trace.substring(0, trace.length() - 3));
return made;
}
public static void main(String[] args) {
System.out.println("Device serial: " + new Device().serial);
build(Kettle::new);
build(() -> new Kettle("Steam", 1.2));
build(Toaster::new);
System.out.println("kWh for a 2200 W kettle running 0.1 h: " + Units.kwh(2200, 0.1));
}
}
Output:
Device serial: unset
Generic kettle, 2200 W, 1.7 L
Appliance(String,int) > Kettle(String,double) > Kettle(String) > Kettle()
Steam kettle, 2200 W, 1.2 L
Appliance(String,int) > Kettle(String,double)
Crisp toaster, 1000 W
Appliance(String,int) > Appliance(String) > Toaster()
kWh for a 2200 W kettle running 0.1 h: 0.22
Points to notice:
new Kettle()goes through threeKettleconstructors and oneApplianceconstructor, but the trace listsAppliancefirst, because the bodies finish in reverse order of the calls.Kettle(String)andKettle()start withthis(...), so they never callsuperdirectly. Only the last constructor in thethischain calls the parent.Toaster()callssuper("Crisp"), which delegates toAppliance(String, int)with the default wattage.Devicehas no constructor in the source, so the compiler-generated one runs, and the field initializer still setsserial.Unitshas only a private constructor, so it can't be instantiated. Its static method works without an instance.
Common questions
Is the default constructor the same as a no-argument constructor? The default constructor is the no-argument constructor the compiler generates. One you write yourself is a no-argument constructor, but it isn't "the default".
Can a constructor call an overridable method? It compiles, but it's risky. The subclass's override runs before the subclass's constructor body has run, so it can see fields that haven't been set yet (article 33).
Are constructors inherited?
No. Each class declares its own constructors. A subclass only calls a parent constructor through super(...).
Do records and enums have constructors?
Yes, with extra rules (compact constructors for records, and always-private constructors for enums). Chapter 7 covers them.
Summary
- Constructors have the class's name and no return type. They can be overloaded and can use any access level, but no other modifiers.
- The compiler adds a public-or-package default constructor only when the class declares no constructors.
- The first statement of a constructor is
this(...)orsuper(...). The compiler insertssuper()if neither is present, and in Java 21, nothing may come before it. - Constructor calls run from the child up to
Object, and the bodies complete from the top down. - A parent without a no-argument constructor forces every subclass constructor to call
super(...)with arguments. Java 25 allows code beforesuper(...)that doesn't touchthis.
Practice quiz
Test yourself with the constructors quiz: 10 exam-style questions with explanations.
Previous: Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
Related reading
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
- Java Method Overloading and Overload Resolution (OCP 21)
- Java Pass-by-Value, Returning Objects and Autoboxing (OCP 21)
- Java static Members, Static Initializers and Static Imports (OCP 21)
- Java Access Modifiers: private, Package, protected and public (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.