Skip to content
Veltoryx Technologies
ProLesson 4.2Beginner3 min readUpdated 30 October 2026

Constructors and this

Create objects in a valid state with constructors, overload them, chain them with this(), and understand the default constructor.

In the last lesson we created a Product and then set its fields one by one. That's easy to get wrong: forget one line and the object is half-built. A constructor sets up an object completely, at the moment it's created.

01Writing a constructor

A constructor looks like a method, but it has the same name as the class and no return type:

ConstructorDemo.java
class Account {
    String owner;
    double balance;

    Account(String owner, double openingBalance) {
        this.owner = owner;              // this.owner is the field; owner is the parameter
        this.balance = openingBalance;
    }

    void deposit(double amount) {
        balance += amount;
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        Account acc = new Account("Asha", 1000);
        acc.deposit(500);
        System.out.println(acc.owner + ": " + acc.balance);
    }
}
Expected output
Asha: 1500.0

Loading the rest of the lesson…