Constructor in OOP

A constructor is a special method/function that runs automatically when an object is created.

Its main job: initialize the object's state.

class BankAccount {
    String owner;
    double balance;

    BankAccount(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }
}

BankAccount acc = new BankAccount("Sherqo", 1000);

When new BankAccount(...) runs:

  1. Memory for the object is created.
  2. Constructor runs automatically.
  3. owner and balance get initialized.
  4. The object is ready to use.

Common constructor types

Type Meaning Example
Default constructor No arguments; gives default initialization BankAccount()
Parameterized constructor Takes arguments to initialize specific values BankAccount(String name, double balance)
Copy constructor Creates an object by copying another object BankAccount(BankAccount other)
Overloaded constructors Multiple constructors with different parameters BankAccount() + BankAccount(String) + BankAccount(String, double)

Default constructor behavior

If you don't define any constructor, Java automatically provides a no-argument constructor.

Once you define any constructor yourself, Java doesn't provide the default constructor anymore.

If you need both, you must define the no-argument constructor yourself.

class BankAccount {

    // Default
    BankAccount() {
        balance = 0;
    }

    // Parameterized
    BankAccount(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    // Copy
    BankAccount(BankAccount other) {
        this.owner = other.owner;
        this.balance = other.balance;
    }
}

Constructor chaining with this()

A constructor can call another constructor in the same class using this(...). Must be the first statement.

class BankAccount {
    String owner;
    double balance;

    BankAccount() {
        this("Unknown", 0); // calls the parameterized constructor
    }

    BankAccount(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }
}

Avoids repeating init logic across overloaded constructors.