Explain it simply
Explain it simply
Opening a bank account means filling in a form: without a name and an ID number, the clerk will not open it. A constructor is that opening form for an object. The moment you write new Course("Java Basics", 12), the constructor runs automatically and puts the required data into the fields.
A constructor's name must match the class name, and it has no return type at all, not even void. That way an object never has to be born half-finished, like a course with no title: as soon as it is built, it is ready to use.
Problem → Why → Solution
The problem: objects with forgotten fields
Without a constructor, you create the object and then assign fields one by one. Forget one and the compiler says nothing: the object carries on with null or 0. In the code below the second course never gets a title, so it prints "null has 8 lessons.". Worse, trying to write a constructor as void Course(...) silently produces an ordinary method, not a constructor.
public class Main {
public static void main(String[] args) {
Course javaCourse = new Course();
javaCourse.title = "Java Basics";
javaCourse.lessons = 12;
Course sqlCourse = new Course();
sqlCourse.lessons = 8; // forgot sqlCourse.title
sqlCourse.showInfo(); // null has 8 lessons.
}
}
class Course {
String title;
int lessons;
void Course(String t, int n) { // void: this is a METHOD, not a constructor
title = t;
lessons = n;
}
void showInfo() {
System.out.println(title + " has " + lessons + " lessons.");
}
}Why does this happen?
Creating the object and filling its fields are two separate steps, so an incomplete object exists in between. Ask for the required data as constructor parameters and a call without it, such as new Course(), becomes a compile error, closing the door on incomplete objects. Add void by mistake and Java treats it as a method, quietly falling back to the default constructor.
Core concept: a constructor establishes the object's guarantees
When new Course("Java Basics", 12) runs, Java reserves memory for the object, sets fields to their defaults (0, null), and then runs the matching constructor. Only when the constructor finishes is the reference handed to the caller. That makes the constructor the best place to check the rules that must hold for the object's whole life, its invariants, such as "the title is never blank" or "the price is never negative". If a rule fails, throw an IllegalArgumentException so the object is never created at all.
Parameters are usually named after the fields they fill (String title). Inside the constructor, title then means the parameter, so you reach the field with this.title. Read this.title = title; as "put the parameter title into this object's title field".
If a class declares no constructor at all, the compiler adds a default constructor with no parameters. Write any constructor yourself and that default disappears, so new Course() fails with "constructor Course in class Course cannot be applied to given types". Like overloaded methods, you can declare several constructors with different parameter lists.
One constructor can call another with this(...), which is called constructor chaining. When Course(String title) calls this(title, 0), the validation code lives only in the full constructor instead of being repeated. In Java 21, this(...) must be the first statement in the constructor. final fields must be assigned exactly once by every constructor and can never change afterwards.
A constructor looks like a method but is not one. It runs exactly once per object, cannot be called again later as myCourse.Course(...), and is not inherited by subclasses. To change state after construction, use meaningful methods such as addLesson(), and those methods must keep honouring the rules the constructor established.
- new reserves memory, sets defaults
- The matching constructor is picked
- Any this(...) call runs first
- Validate, then assign the fields
- Only then is the reference returned
If the constructor throws, the caller never receives a reference to the object.
General pattern
class ClassName {
final Type required;
Type optional;
ClassName(Type required, Type optional) { // no return type
// validate first, throw if invalid
this.required = required;
this.optional = optional;
}
ClassName(Type required) {
this(required, defaultValue); // must be the first statement
}
}The constructor is named after the class and has no return type. The full constructor validates and assigns, while shorter ones fill in defaults and delegate with this(...).
Example: a Course with validation and chaining
This Course class has two constructors. The two-parameter version validates the title and assigns the fields; the title-only version is for a draft course with no lessons yet and delegates with this(title, 0). The end of main tries to build a course with a blank title. try/catch is covered properly in the Exceptions lesson; here it simply lets us print the error message instead of stopping the program.
public class Main {
public static void main(String[] args) {
Course javaCourse = new Course("Java Basics", 12);
javaCourse.showInfo();
Course draft = new Course("Kotlin Basics");
draft.showInfo();
try {
new Course(" ", 5);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
class Course {
final String title;
int lessons;
Course(String title, int lessons) {
if (title == null || title.isBlank()) {
throw new IllegalArgumentException("title is required");
}
this.title = title;
this.lessons = lessons;
}
Course(String title) {
this(title, 0); // a draft course starts with no lessons
}
void showInfo() {
System.out.println(title + " has " + lessons + " lessons.");
}
}Code breakdown
- Constructor header
Course(String title, int lessons) {It matches the class name Course and has no return type, so it is a constructor. Writing void Course(...) would make it a method.
- Guarding the invariant
throw new IllegalArgumentException("title is required");A null or whitespace-only title throws, so no Course with a bad title can ever enter the program. isBlank() exists since Java 11.
- Field vs parameter
this.title = title;On the left, this.title is the field; on the right, title is the parameter. Drop this. and the parameter is assigned to itself, and because the field is final, the code would not even compile.
- Constructor chaining
this(title, 0); // a draft course starts with no lessonsIt calls the two-parameter constructor, so the blank-title check also protects draft courses. This line must be the constructor's first statement.
- Choosing a constructor
Course draft = new Course("Kotlin Basics");With one argument, the compiler picks Course(String), exactly like overload resolution. The result is "Kotlin Basics has 0 lessons.".
Java Basics has 12 lessons.
Kotlin Basics has 0 lessons.
Rejected: title is requiredA record's compact constructor
A record automatically gets a canonical constructor that takes every component as a parameter and assigns the fields. To add validation, write a compact constructor with no parameter list: you write only the checks, and the compiler appends assignments such as this.amount = amount afterwards. For value types that never change, such as money amounts, coordinates or date ranges, this is the shortest and safest shape.
public class Main {
public static void main(String[] args) {
Money price = new Money(2500, "MMK");
System.out.println(price);
System.out.println(price.amount() + " " + price.currency());
try {
new Money(-1, "MMK");
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
record Money(long amount, String currency) {
Money { // compact constructor: no parameter list
if (amount < 0) {
throw new IllegalArgumentException("amount must not be negative");
}
}
}The output is Money[amount=2500, currency=MMK], then 2500 MMK, then Rejected: amount must not be negative.
In real projects
Where this shows up in real projects
When creating a user account, the email and username, or for a Product the name and price, are required, so they become constructor parameters. Then no other part of the code ever has to check for "a user without an email": the constructor already guarantees it. Domain-driven design calls this an always-valid object, and it removes an entire class of bugs.
In frameworks such as Spring, constructor injection is the standard style: a constructor like OrderService(PaymentGateway gateway, OrderRepository repo) receives the dependencies and stores them in final fields. Every service object therefore has all its dependencies, and in tests you simply pass a fake gateway to the constructor. For classes with many optional fields, teams usually switch to the builder pattern rather than writing a constructor with ten parameters.
Common mistakes
Common mistakes
1. Giving the constructor a void return type
void Course(String t, int n) is a method, so new Course("Java", 12) fails with "constructor Course in class Course cannot be applied to given types": the default constructor the compiler added takes no arguments. Remove the void.
2. Forgetting this. and assigning a parameter to itself
Course(String title, int lessons) { title = title; lessons = lessons; } compiles, yet never touches the fields, so it prints "null has 0 lessons.". Write this.title = title;, and make the field final so the compiler catches the slip.
3. Adding a constructor and still calling new X()
Declaring any constructor removes the default one, so every existing new Course() suddenly fails to compile. If you genuinely need it, write a no-argument constructor yourself that delegates with this(...) and sensible defaults.
Best practices
Best practices
- Keep validation in one full constructor and chain the others to it with this(...).
- Make fields that never change final.
- Use the constructor only to set the object up; avoid heavy work such as network calls or reading files there.
Mini challenge
Mini challenge: a validated Product
Write a Product class for a shop with two constructors. No product may ever be created with an invalid price or stock.
- Fields: final String name, final int priceKyat, int stock
- Product(name, priceKyat, stock) throws IllegalArgumentException with "price must be positive" when price <= 0 and "stock cannot be negative" when stock < 0
- Product(name, priceKyat) chains with this(...) and a stock of 0
- describe() prints a line like "Green Tea - 1500 MMK, stock 40"
public class Main {
public static void main(String[] args) {
// TODO: tea = Green Tea, 1500, 40; cake = Cheesecake, 4500 (no stock given)
// TODO: call describe() on both
// TODO: try a price of 0 and a stock of -2, printing "Rejected: " + message
}
}
class Product {
// TODO: final name, final priceKyat, stock
// TODO: Product(String name, int priceKyat, int stock) with validation
// TODO: Product(String name, int priceKyat) chaining with this(...)
void describe() {
// TODO: "<name> - <price> MMK, stock <stock>"
}
}Expected: Green Tea - 1500 MMK, stock 40 Cheesecake - 4500 MMK, stock 0 Rejected: price must be positive Rejected: stock cannot be negative
Show hint
Assign the final fields only after validation passes. Product(String, int) needs just one line: this(name, priceKyat, 0);. Test the invalid products with try { new Product(...); } catch (IllegalArgumentException e) { ... }.
Show solution
public class Main {
public static void main(String[] args) {
Product tea = new Product("Green Tea", 1500, 40);
Product cake = new Product("Cheesecake", 4500);
tea.describe();
cake.describe();
try {
new Product("Ghost", 0, 5);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
try {
new Product("Ghost", 900, -2);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
class Product {
final String name;
final int priceKyat;
int stock;
Product(String name, int priceKyat, int stock) {
if (priceKyat <= 0) {
throw new IllegalArgumentException("price must be positive");
}
if (stock < 0) {
throw new IllegalArgumentException("stock cannot be negative");
}
this.name = name;
this.priceKyat = priceKyat;
this.stock = stock;
}
Product(String name, int priceKyat) {
this(name, priceKyat, 0);
}
void describe() {
System.out.println(name + " - " + priceKyat + " MMK, stock " + stock);
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A constructor matches the class name, has no return type and runs automatically on every new.
- When a field and a parameter share a name, write this.field = param.
- Declaring any constructor removes the default constructor.
- Chain with this(...) to keep validation in one place, so an invalid object is never created.