Lesson 3 of 518 minModule progress 0%

Module 5: Classes, Objects, and Constructors

Constructors

Use constructors to create objects with sensible starting values instead of manually filling every field after creation.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-16

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, edited by hand, and checked against current Java 25 documentation and runnable examples.

Learning goals

  • Recognize a constructor in a Java class
  • Use constructors to initialize object fields
  • Understand the difference between no-arg and parameterized constructors

A constructor runs when an object is created: It prepares the object’s starting state.

Constructor names match the class name: A constructor has no return type, not even void.

No-arg and parameterized forms both matter: A no-arg constructor sets defaults, while a parameterized constructor lets the caller choose the starting values.

Why this matters: Constructors help objects begin in a valid and predictable state.

Runnable examples

A constructor sets starting values

class User {
    String name;

    User(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        User user = new User("Amina");
        System.out.println(user.name);
    }
}

Expected output

Amina

A no-arg constructor can set defaults

class Account {
    String owner;
    int level;

    Account() {
        owner = "Guest";
        level = 1;
    }
}

public class Main {
    public static void main(String[] args) {
        Account account = new Account();
        System.out.println(account.owner);
        System.out.println(account.level);
    }
}

Expected output

Guest
1

Common mistakes

Adding a return type to a constructor

Constructors have the same name as the class and no return type at all.

Mini exercise

Create a `Movie` class with a constructor that accepts a title and year.

Summary

  • Constructors initialize new objects.
  • They have the same name as the class.
  • Parameter values can be used to start the object correctly.

Next step

Now use `this` to make field assignment clearer when constructor parameters match field names.

Sources used

Advertisement

Lesson check

What makes a constructor different from a normal method?

Next lesson →