Beginner · Classes and objects · topic 17 of 60 · 25 min
Constructors and this
Explanation
Why constructors?
In the last topic we created an account and then set its fields one by one. It is easy to forget one and end up with an account that has no owner. A constructor runs automatically when the object is created and makes sure it starts in a valid state.
public class BankAccount {
private final String owner;
private double balance;
public BankAccount(String owner, double openingBalance) { // no return type
if (owner == null || owner.isBlank()) throw new IllegalArgumentException("Owner required");
if (openingBalance < 0) throw new IllegalArgumentException("Negative opening balance");
this.owner = owner; // this.owner = the field; owner = the parameter
this.balance = openingBalance;
}
}
BankAccount acc = new BankAccount("Asha", 1000);this: the field versus the parameter
When a parameter has the same name as a field, the parameter "shadows" the field inside the constructor. owner = owner; would just assign the parameter to itself and leave the field null. this.owner refers to the field of the object being built.
Overloaded constructors and this(...)
public class Product {
private final String name;
private final double price;
private int stock;
public Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public Product(String name, double price) {
this(name, price, 0); // call the 3-argument constructor; must be the first statement
}
}
Product a = new Product("Pen", 20, 100);
Product b = new Product("Notebook", 60); // stock 0The default constructor
If a class has no constructor at all, the compiler adds an invisible public no-argument constructor that does nothing special. As soon as you write any constructor, that default one is NOT added. Then new Product() no longer compiles unless you write a no-argument constructor yourself.
class Box { int size; }
new Box(); // fine: default constructor exists
class Crate { int size; Crate(int size) { this.size = size; } }
// new Crate(); // compile error: constructor Crate in class Crate cannot be applied to given typesInitialisation order (simplified)
- Fields get default values (0, null…).
- Field initialisers run in the order written (private int stock = 10;).
- The constructor body runs.
Inheritance adds one more step (the parent's constructor runs first), which module 5 covers.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Constructors and this · 1/6
In this lesson you will make sure every object starts in a valid state, using constructors.
Prefer a video by a teacher? Find free videos on “java constructors this keyword constructor chaining overloading” on YouTube ↗
In real life: Creating train bookings
A ticket system creates a Booking with the PNR, passenger name and train number. A second constructor generates a PNR automatically when none is given. Both run the same checks through this(...).
class Booking {
private static int nextPnr = 4_521_000;
private final String pnr, passenger;
private final int train;
Booking(String pnr, String passenger, int train) {
if (passenger == null || passenger.isBlank()) throw new IllegalArgumentException("Passenger name required");
this.pnr = pnr; this.passenger = passenger; this.train = train;
}
Booking(String passenger, int train) {
this(String.valueOf(nextPnr++), passenger, train);
}
}Practice (0/3 done)
What does this print? class P { int x; P(int x) { x = x; } } … System.out.println(new P(5).x);
class Car { Car(String model) { … } } Which line does NOT compile?
Write a class Product with private final fields name and price and a private int stock. Add a 3-argument constructor that rejects a blank name, a negative price or negative stock with IllegalArgumentException, and a 2-argument constructor that chains to it with stock 0. Create one valid product and try to create an invalid one inside try/catch.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Encapsulation: private fields, getters and settersClasses and objects · same module
- static members and finalClasses and objects · same module
- Classes, objects and constructorsC# and .NET · Classes and objects
- Classes and constructorsFlutter and Dart · Null safety and object-oriented Dart
- Constructors and destructorsC++ Programming (modern C++ and DSA) · Classes, constructors and RAII
- Inheritance with extendsInheritance, polymorphism and interfaces
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the return type of a constructor?
Answer: It has none
Constructors have no return type, not even void.
Where must this(...) appear in a constructor?
Answer: As the first statement
A constructor call must be the first statement.
When does Java add a default no-argument constructor?
Answer: Only when the class declares no constructor at all
Writing any constructor removes the default one.
What is the main job of a constructor?
Answer: To put a new object into a valid initial state
Constructors initialise objects.
What does : this(name, 0m) after a constructor header do?Related
Answer: Calls another constructor of the same class first
It chains to another constructor to reuse its setup code.
Why do Flutter widgets often use const constructors?Related
Answer: Constant widgets are created once and can be skipped during rebuilds
const saves work at run time.
Why mark a one-argument constructor explicit?Related
Answer: To stop silent implicit conversions from that argument type
explicit prevents surprises such as passing 42 where a Counter is expected.
Is Java pass-by-value or pass-by-reference?Related
Answer: Always pass-by-value (references are copied for objects)
Java copies every argument; for objects, the copy is the reference.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Classes and objects” before its exam: Encapsulation: private fields, getters and setters, static members and final, toString, equals, hashCode and records.
- Module 4 exam: Classes and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Inheritance, polymorphism and interfaces. 60 topics left in the course before the final exam.