Java Learner logo

Module 5: Object-Oriented Programming (OOP) Fundamentals

Lesson focus

Constructors

Learn how to use constructors to initialize the state of an object when it is created. Covers default constructors, parameterized constructors, and constructor overloading.

What is a Constructor? A constructor is a special method that is called when an object is created. Its primary purpose is to initialize the fields of the object.

Rules for Constructors:

  • A constructor must have the same name as the class.
  • A constructor cannot have a return type (not even void).

Default Constructor: If you do not define any constructor in your class, the Java compiler provides a default, no-argument constructor for you. This constructor initializes fields to their default values (0 for numbers, false for booleans, null for objects).

Parameterized Constructor: You can define your own constructor that accepts parameters. This is the best way to ensure that an object is created in a valid state.

Constructor Overloading: Just like methods, constructors can be overloaded. You can have multiple constructors with the same name but different parameter lists.

The this Keyword: Inside a constructor, the this keyword is a reference to the current object being created. It is often used to disambiguate between instance variables and parameters with the same name.

class User {
    String username;
    int level;

    // Default (no-arg) constructor
    public User() {
        this.username = "Guest";
        this.level = 1;
    }

    // Parameterized constructor
    public User(String username, int level) {
        this.username = username;
        this.level = level;
    }
}

User guest = new User(); // Calls the default constructor
User proUser = new User("Alice", 10); // Calls the parameterized constructor

Lesson quiz

What is the primary purpose of a constructor?

Next lesson →