Constructors

Lesson 0005 — 30 min read

A constructor is a special method automatically called when an object is created. It initializes the object's state.

Key Rules (All Languages)

Default Constructor Behavior

Language Default constructor provided? Auto-initializes fields?
Java Yes, if no constructor defined Yes — 0, 0.0, null, false
C++ Yes, if no constructor defined No — garbage values for primitives; use {} for zero-init
Python Default __init__ (no-op) No — attributes must be assigned explicitly

Basic Constructor Example

class Employee {
    private int salary;
    public String employeeName;

    public Employee() {
        employeeName = "John Doe";
        salary = 5000;
    }
}
class Employee {
private:
    int salary;
public:
    string employeeName;

    Employee() {
        employeeName = "John Doe";
        salary = 5000;
    }
};
class Employee:
    def __init__(self):
        self.__salary = 5000
        self.employeeName = "John Doe"

Types of Constructors

1. Non-parameterized

Takes no arguments. Sets default values.

// Java
public Employee() {
    employeeName = "Unknown";
    salary = 0;
}

2. Parameterized

Accepts arguments to set specific values at creation.

// Java
public Employee(String name, int salary) {
    this.employeeName = name;
    this.salary = salary;
}

// Usage
Employee e = new Employee("Raj", 10000);

The this keyword refers to the current instance — used to disambiguate when parameter names match field names.

3. Copy Constructor

Creates a new object by copying another.

Employee(const Employee &emp) {
    this->employeeName = emp.employeeName;
    this->salary = emp.salary;
}

Employee obj2(obj1);  // copy constructor called
public Employee(Employee emp) {
    this(emp.employeeName, emp.salary);  // chaining to parameterized
}

Employee obj2 = new Employee(obj1);
@classmethod
def from_employee(cls, other):
    return cls(other.name, other.salary)

emp2 = Employee.from_employee(emp1)

# Or use copy module
import copy
emp3 = copy.copy(emp1)      # shallow
emp4 = copy.deepcopy(emp1)  # deep

Constructor Overloading

Multiple constructors with different parameter lists — objects can be initialized in different ways.

Java / C++ (native support)

public Employee() { ... }
public Employee(String name) { ... }
public Employee(String name, int salary) { ... }

Python (simulated)

def __init__(self, name="Unknown", salary=0):
    self.name = name
    self.salary = salary

# Alternative via class methods
@classmethod
def from_string(cls, data):
    name, salary = data.split(",")
    return cls(name.strip(), int(salary.strip()))

Constructor Chaining

One constructor calls another to avoid repeating initialization logic.

Java (this())

public Employee(String n, int s) {
    name = n;
    salary = s;
}

public Employee(String n)   { this(n, 0); }
public Employee()            { this("Unknown", 0); }

C++ (initializer list delegation, C++11)

Employee(string n, int s) : name(n), salary(s) {}
Employee(string n) : Employee(n, 0) {}
Employee() : Employee("Unknown", 0) {}

Python (super().__init__())

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Student(Person):
    def __init__(self, name, age, roll_no):
        super().__init__(name, age)  # parent constructor
        self.roll_no = roll_no

Purpose of Constructors

Code trace: What does this print?

class A {
    int x;
    A() { this(10); }
    A(int x) { this.x = x; }
}

A obj = new A();
System.out.println(obj.x);

In C++, what are the values of a and b after this construction?

class Point {
    int a, b;
public:
    Point() : b(5), a(b) { }
};

Point p;

Notes

Constructor :-

Constructor ⇒ special method ; auto-called on object creation

Rules ⇒ same name as class ; no return type ; auto-runs

Types :-

a) Non-parameterized ⇒ no args ; sets default values

b) Parameterized ⇒ accepts args for specific object initialization

c) Copy constructor ⇒ creates new object by copying state of existing object

Language Differences :-

Default constructor behavior:

a) Java ⇒ compiler generates if none defined ; auto-initializes fields (0, null, false)

b) C++ ⇒ compiler generates if none defined ; leaves primitives with garbage values

c) Python ⇒ default __init__ (no-op) ; no automatic field assignment

Copy constructor:

a) C++ ⇒ built-in copy constructor concept

b) Java ⇒ manual copy constructor (or clone())

c) Python ⇒ classmethods or copy module (shallow vs deep copy)

Overloading :-

Java/C++ ⇒ native support ; multiple constructors with different parameter signatures

Python ⇒ simulated via default parameter values or @classmethod factory methods

Chaining :-

Goal ⇒ avoid repeating initialization logic

a) Java ⇒ this() calls sibling constructor in same class

b) C++ ⇒ initializer list delegation (eg : Employee(n, 0))

c) Python ⇒ super().__init__() for parent constructor chaining

Primary source: Oracle Java Tutorials — Constructors. Ask me anything that's unclear.

← Prev: Attributes & Methods Next: Encapsulation →

Questions? Ask your agent — you can follow up on any concept, quiz answer, or how this applies to a specific coding problem. Review the Java glossary or syntax quick reference for a compressed overview.