Object Construction

Introduction

Object construction is the process of creating and initializing objects. Constructors are special methods used for this purpose.


Constructor Basics

Characteristics:

  • Same name as class
  • No return type (not even void)
  • Called automatically when object is created
  • Used to initialize object state

Syntax:

class ClassName {
    // Constructor
    ClassName() {
        // Initialization code
    }
}

Simple Constructor Example

class Student {
    String name;
    int rollNo;

    // Constructor
    Student() {
        name = "Unknown";
        rollNo = 0;
        System.out.println("Student object created");
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();  // Constructor called
        System.out.println(s.name);     // Unknown
        System.out.println(s.rollNo);   // 0
    }
}

Parameterized Constructor

Accepts arguments to initialize fields.

class Student {
    String name;
    int rollNo;

    // Parameterized constructor
    Student(String n, int r) {
        name = n;
        rollNo = r;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll No: " + rollNo);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("John", 101);
        Student s2 = new Student("Alice", 102);

        s1.display();
        s2.display();
    }
}

Default Constructor

If no constructor is defined, Java provides a default constructor.

// No constructor defined
class Student {
    String name;
    int rollNo;
}

// Java automatically provides:
// Student() { }

public class Main {
    public static void main(String[] args) {
        Student s = new Student();  // Uses default constructor
        s.name = "John";
        s.rollNo = 101;
    }
}

Note: Once you define any constructor, default constructor is NOT provided.


Constructor Overloading

Multiple constructors with different parameters.

class Rectangle {
    double length;
    double width;

    // No-argument constructor
    Rectangle() {
        length = 1.0;
        width = 1.0;
    }

    // Constructor with one parameter
    Rectangle(double side) {
        length = side;
        width = side;
    }

    // Constructor with two parameters
    Rectangle(double l, double w) {
        length = l;
        width = w;
    }

    void display() {
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();      // 1x1
        Rectangle r2 = new Rectangle(5);     // 5x5 square
        Rectangle r3 = new Rectangle(4, 6);  // 4x6 rectangle

        r1.display();
        r2.display();
        r3.display();
    }
}

Using ‘this’ in Constructor

class Student {
    String name;
    int rollNo;

    Student(String name, int rollNo) {
        this.name = name;      // this.name = field, name = parameter
        this.rollNo = rollNo;
    }
}

Constructor Chaining

One constructor calling another using this().

class Student {
    String name;
    int rollNo;
    double marks;

    // Constructor 1
    Student() {
        this("Unknown", 0, 0.0);  // Call constructor 3
    }

    // Constructor 2
    Student(String name, int rollNo) {
        this(name, rollNo, 0.0);  // Call constructor 3
    }

    // Constructor 3 (main constructor)
    Student(String name, int rollNo, double marks) {
        this.name = name;
        this.rollNo = rollNo;
        this.marks = marks;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student("John", 101);
        Student s3 = new Student("Alice", 102, 85.5);
    }
}

Copy Constructor

Creates object by copying another object.

class Student {
    String name;
    int rollNo;

    // Regular constructor
    Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
    }

    // Copy constructor
    Student(Student other) {
        this.name = other.name;
        this.rollNo = other.rollNo;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("John", 101);
        Student s2 = new Student(s1);  // Copy s1

        System.out.println(s2.name);    // John
        System.out.println(s2.rollNo);  // 101
    }
}

Complete Example

class BankAccount {
    private String accountNumber;
    private String holderName;
    private double balance;

    // Default constructor
    public BankAccount() {
        this.accountNumber = "0000000000";
        this.holderName = "Unknown";
        this.balance = 0.0;
    }

    // Parameterized constructor
    public BankAccount(String accountNumber, String holderName) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = 0.0;
    }

    // Full constructor
    public BankAccount(String accountNumber, String holderName, double balance) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = balance;
    }

    public void display() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Holder: " + holderName);
        System.out.println("Balance: " + balance);
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount();
        BankAccount acc2 = new BankAccount("1234567890", "John");
        BankAccount acc3 = new BankAccount("9876543210", "Alice", 5000);

        acc1.display();
        acc2.display();
        acc3.display();
    }
}

Constructor vs Method

ConstructorMethod
Same name as classAny name
No return typeHas return type
Called automaticallyCalled explicitly
Used for initializationUsed for operations
Cannot be inheritedCan be inherited
new ClassName()obj.methodName()

Object Creation Steps

Student s = new Student("John", 101);

Steps:

  1. Memory allocated for object
  2. Fields initialized to default values
  3. Constructor called
  4. Fields initialized as per constructor
  5. Reference returned to variable

Constructor Rules

  1. Name must match class name
  2. No return type (not even void)
  3. Can be overloaded
  4. Cannot be abstract, static, or final
  5. this() must be first statement if used
  6. Default constructor provided only if no constructor defined

Common Patterns

Pattern 1: Validation in Constructor

class Person {
    String name;
    int age;

    Person(String name, int age) {
        if (age > 0) {
            this.age = age;
        } else {
            this.age = 0;
        }
        this.name = name;
    }
}

Pattern 2: Counting Objects

class Counter {
    static int count = 0;

    Counter() {
        count++;
    }

    static int getCount() {
        return count;
    }
}

Quick Reference

class Example {
    int value;

    // Default constructor
    Example() {
        value = 0;
    }

    // Parameterized
    Example(int value) {
        this.value = value;
    }

    // Copy constructor
    Example(Example other) {
        this.value = other.value;
    }
}

// Usage
Example e1 = new Example();      // Default
Example e2 = new Example(10);    // Parameterized
Example e3 = new Example(e2);    // Copy

Exam Tips

Remember:

  1. Constructor same name as class
  2. No return type
  3. Called automatically with new
  4. Used for initialization
  5. Can be overloaded
  6. Default constructor auto-provided
  7. Use this() for constructor chaining
  8. this() must be first statement
  9. Cannot be static or abstract
  10. Different from methods

Common Questions:

  • What is constructor?
  • Constructor vs method?
  • Types of constructors?
  • What is default constructor?
  • What is constructor overloading?
  • What is constructor chaining?
  • Can constructor be static?
  • Rules for constructors?