Table of Contents

    Constructor

    Chapter 16.6

    Constructor in Object-Oriented Programming

    Learn what a constructor is in Object-Oriented Programming, why constructors are used, how they initialize objects, different types of constructors, constructor overloading, default values, validation, and real-world examples.

    Introduction

    In Object-Oriented Programming, a constructor is a special method that is used to initialize an object when it is created. When we create an object from a class, the object usually needs some initial values. A constructor helps assign those initial values automatically.

    For example, when we create a Student object, we may want to set the student's name, roll number, course, and marks immediately. Instead of assigning these values one by one after creating the object, we can use a constructor to initialize them at the time of object creation.

    Constructors are very important because they make sure that an object starts its life in a valid and meaningful state. Without proper initialization, an object may contain empty, default, or incorrect values, which can cause errors later in the program.

    "A constructor is a special method that runs automatically when an object is created and initializes the object."

    Simple Definition of Constructor

    A constructor is a special member of a class that is automatically called when an object is created. Its main purpose is to initialize the properties of the object.

    In simple words:

    • A constructor is used to create and initialize objects.
    • It runs automatically when an object is created.
    • It usually sets initial values for object properties.
    • It helps avoid uninitialized or invalid object data.
    • It may accept parameters to initialize objects with custom values.
    • It is usually defined inside a class.
    CONSTRUCTOR CONCEPT
    Constructor = Object Creation + Initial Values
    Important: A constructor is not usually called like a normal method. It is called automatically when an object is created.

    Why Do We Need Constructors?

    Constructors are needed because objects often require initial data before they can be used properly. If an object is created without important values, the program may behave incorrectly.

    Suppose we are creating a BankAccount object. It should have an account number, account holder name, and initial balance. If these values are missing, the bank account object is not meaningful.

    Without Constructor

    • Object may be created with empty values.
    • Properties must be assigned manually one by one.
    • Important values may be forgotten.
    • Object may enter an invalid state.
    • Code becomes repetitive.
    • Initialization logic may be scattered.

    With Constructor

    • Object receives values at creation time.
    • Important properties are initialized automatically.
    • Code becomes cleaner and shorter.
    • Object starts in a valid state.
    • Initialization logic stays inside the class.
    • Object creation becomes more controlled.

    Real-World Analogy of Constructor

    To understand constructors easily, imagine a school admission process. When a new student is admitted, the school collects important information such as name, roll number, course, and contact number. After this information is collected, the student record becomes ready to use.

    Similarly, when an object is created in programming, the constructor collects or assigns the initial data required by the object.

    Constructor as an Admission Form

    Just like an admission form initializes a student's record with required details, a constructor initializes an object with required values when it is created.

    Constructor and Object Initialization

    Object initialization means assigning initial values to the properties of an object. A constructor is one of the most common ways to initialize an object.

    For example, if a Student class has properties such as name, rollNumber, and marks, then a constructor can assign values to these properties when the student object is created.

    OBJECT INITIALIZATION
    Object gets initial values through Constructor
    
    // Conceptual constructor example
    
    Class Student
    {
        name
        rollNumber
        marks
    
        Constructor Student(studentName, studentRollNumber, studentMarks)
        {
            name = studentName
            rollNumber = studentRollNumber
            marks = studentMarks
        }
    }
    

    In this conceptual example, the constructor receives values and assigns them to the object's properties.

    Basic Structure of a Constructor

    The exact syntax of a constructor depends on the programming language. However, the general purpose remains the same: initialize the object.

    
    // General conceptual constructor structure
    
    Class ClassName
    {
        property1
        property2
    
        Constructor ClassName(value1, value2)
        {
            property1 = value1
            property2 = value2
        }
    }
    

    A constructor usually contains:

    Part Meaning Example
    Constructor Name Name used to identify the constructor. Student()
    Parameters Input values passed during object creation. name, rollNumber, marks
    Constructor Body Code that initializes object properties. this.name = name;
    Initialization Logic Rules used to assign and validate initial values. marks should be between 0 and 100

    Java Example of Constructor

    In Java, a constructor has the same name as the class and does not have a return type. It is automatically called when an object is created using the new keyword.

    Prerequisites: To understand this example, you should know basic Java syntax, classes, objects, properties, methods, parameters, and the main method.
    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        // Constructor
        Student(String studentName, int studentRollNumber, int studentMarks) {
            name = studentName;
            rollNumber = studentRollNumber;
            marks = studentMarks;
        }
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            // Constructor is called automatically here
            Student student1 = new Student("Rahul", 101, 85);
    
            student1.displayDetails();
        }
    }
    

    In this example, Student(String studentName, int studentRollNumber, int studentMarks) is the constructor. It initializes the name, rollNumber, and marks properties when the object is created.

    JavaScript Example of Constructor

    In JavaScript classes, the constructor is written using the special keyword constructor. It is automatically called when an object is created using the new keyword.

    Prerequisites: To understand this example, you should know JavaScript variables, classes, objects, methods, the this keyword, and console output.
    
    class Student {
    
        constructor(name, rollNumber, marks) {
            this.name = name;
            this.rollNumber = rollNumber;
            this.marks = marks;
        }
    
        displayDetails() {
            console.log("Name: " + this.name);
            console.log("Roll Number: " + this.rollNumber);
            console.log("Marks: " + this.marks);
        }
    }
    
    const student1 = new Student("Ayesha", 102, 92);
    
    student1.displayDetails();
    

    In this JavaScript example, the constructor initializes the properties of the student1 object. The keyword this refers to the current object being created.

    Constructor and the Dot Operator

    A constructor initializes the object. After the object is created, we can access its properties and methods using the dot operator.

    AFTER CONSTRUCTION
    objectName.propertyName   |   objectName.methodName()
    
    Student student1 = new Student("Rahul", 101, 85);
    
    System.out.println(student1.name);
    
    student1.displayDetails();
    

    Here, the constructor creates and initializes the object. After that, the object can access its members using the dot operator.

    Types of Constructors

    Constructors can be of different types depending on how they receive values and initialize the object. The most common types are default constructor, parameterized constructor, copy constructor, and private constructor.

    1

    Default Constructor

    Constructor with no parameters

    A default constructor does not accept any arguments. It initializes the object with default values. In some languages, if we do not write any constructor, the compiler or runtime may provide a default constructor automatically.

    Example Student() creates a student object without receiving custom values.
    2

    Parameterized Constructor

    Constructor with parameters

    A parameterized constructor accepts values during object creation and uses those values to initialize object properties.

    Example Student("Rahul", 101, 85) initializes a student object with specific values.
    3

    Copy Constructor

    Constructor that creates a new object using another object

    A copy constructor is used to create a new object by copying values from an existing object. This concept is common in languages such as C++ and can also be implemented manually in other languages.

    Example Creating student2 by copying values from student1.
    4

    Private Constructor

    Constructor that cannot be accessed directly from outside the class

    A private constructor is used when we want to control object creation. It is commonly used in special design patterns or utility classes depending on the programming language.

    Example Preventing direct object creation from outside the class.

    Default Constructor

    A default constructor is a constructor that does not take any parameters. It is useful when we want to create an object first and assign values later, or when we want to set predefined default values.

    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        // Default constructor
        Student() {
            name = "Unknown";
            rollNumber = 0;
            marks = 0;
        }
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student();
    
            student1.displayDetails();
        }
    }
    

    In this example, the default constructor assigns default values to the properties of the student object.

    Parameterized Constructor

    A parameterized constructor accepts values as input and uses those values to initialize the object. It is useful when we want to create an object with specific values immediately.

    
    class Product {
    
        String productName;
        double price;
        int stockQuantity;
    
        // Parameterized constructor
        Product(String name, double productPrice, int stock) {
            productName = name;
            price = productPrice;
            stockQuantity = stock;
        }
    
        void displayProduct() {
            System.out.println("Product Name: " + productName);
            System.out.println("Price: " + price);
            System.out.println("Stock Quantity: " + stockQuantity);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Product product1 = new Product("Keyboard", 1200.50, 10);
    
            product1.displayProduct();
        }
    }
    

    Here, the Product constructor receives product name, price, and stock quantity during object creation.

    Copy Constructor Concept

    A copy constructor creates a new object using the values of an existing object. This is useful when we want a new object with the same data as another object.

    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        Student(String studentName, int studentRollNumber, int studentMarks) {
            name = studentName;
            rollNumber = studentRollNumber;
            marks = studentMarks;
        }
    
        // Copy constructor
        Student(Student existingStudent) {
            name = existingStudent.name;
            rollNumber = existingStudent.rollNumber;
            marks = existingStudent.marks;
        }
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student("Rahul", 101, 85);
    
            Student student2 = new Student(student1);
    
            student2.displayDetails();
        }
    }
    

    In this example, student2 is created by copying values from student1.

    Constructor Overloading

    Constructor overloading means creating multiple constructors in the same class with different parameter lists. This allows objects to be created in different ways.

    For example, a Student object may be created with no values, with only name, or with full details.

    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        // Constructor 1: No parameters
        Student() {
            name = "Unknown";
            rollNumber = 0;
            marks = 0;
        }
    
        // Constructor 2: One parameter
        Student(String studentName) {
            name = studentName;
            rollNumber = 0;
            marks = 0;
        }
    
        // Constructor 3: Three parameters
        Student(String studentName, int studentRollNumber, int studentMarks) {
            name = studentName;
            rollNumber = studentRollNumber;
            marks = studentMarks;
        }
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student();
            Student student2 = new Student("Ayesha");
            Student student3 = new Student("Rahul", 101, 85);
    
            student1.displayDetails();
            student2.displayDetails();
            student3.displayDetails();
        }
    }
    

    In this example, the Student class has three constructors. Each constructor initializes the object in a different way.

    Important: Constructor overloading allows flexible object creation while keeping initialization logic inside the class.

    Validation Inside Constructor

    Constructors can also contain validation logic. This means we can check whether the provided values are valid before assigning them to object properties.

    For example, marks should not be negative and should not be greater than 100. A constructor can check this rule before assigning the value.

    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        Student(String studentName, int studentRollNumber, int studentMarks) {
            name = studentName;
            rollNumber = studentRollNumber;
    
            if (studentMarks >= 0 && studentMarks <= 100) {
                marks = studentMarks;
            } else {
                marks = 0;
                System.out.println("Invalid marks. Default marks assigned as 0.");
            }
        }
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    

    In this example, the constructor protects the object from invalid marks values.

    Constructor and Encapsulation

    Constructors support encapsulation because they help control how an object is initialized. Instead of allowing external code to freely assign values, the constructor can define the correct way to create an object.

    For example, in a BankAccount class, the initial balance should not be negative. The constructor can enforce this rule during object creation.

    
    class BankAccount {
    
        private String accountNumber;
        private String accountHolderName;
        private double balance;
    
        BankAccount(String number, String holderName, double initialBalance) {
            accountNumber = number;
            accountHolderName = holderName;
    
            if (initialBalance >= 0) {
                balance = initialBalance;
            } else {
                balance = 0;
            }
        }
    
        void displayAccountDetails() {
            System.out.println("Account Number: " + accountNumber);
            System.out.println("Account Holder: " + accountHolderName);
            System.out.println("Balance: " + balance);
        }
    }
    

    In this example, the constructor protects the balance property from being initialized with a negative value.

    Constructor vs Method

    Constructors and methods may look similar because both contain code blocks inside a class. However, their purposes are different. A constructor initializes an object, while a method performs an action after the object is created.

    Basis Constructor Method
    Purpose Initializes an object. Performs an action or behavior.
    Calling Called automatically when object is created. Called manually using object or class name.
    Return Type Usually does not have a return type. Can have a return type or be void.
    Name Often same as class name in many languages. Can have any valid method name.
    Execution Time Runs during object creation. Runs when explicitly called.
    Example new Student("Rahul", 101, 85) student1.displayDetails()

    Constructor vs Setter Method

    Both constructors and setter methods can assign values to object properties, but they are used at different times. A constructor initializes values during object creation, while setter methods update values after object creation.

    Basis Constructor Setter Method
    When Used During object creation. After object creation.
    Main Purpose Initializes required object data. Updates property values later.
    Calling Automatic during object creation. Called manually.
    Best Use Required initial values. Changing optional or updateable values.
    Example Student("Rahul", 101) setMarks(85)

    Real-World Example: Bank Account Constructor

    A bank account object should be created with important information such as account number, holder name, and initial balance. A constructor ensures that these values are provided during object creation.

    
    class BankAccount {
    
        private String accountNumber;
        private String accountHolderName;
        private double balance;
    
        BankAccount(String number, String holderName, double initialBalance) {
            accountNumber = number;
            accountHolderName = holderName;
    
            if (initialBalance >= 0) {
                balance = initialBalance;
            } else {
                balance = 0;
            }
        }
    
        void deposit(double amount) {
            if (amount > 0) {
                balance = balance + amount;
            }
        }
    
        void withdraw(double amount) {
            if (amount > 0 && amount <= balance) {
                balance = balance - amount;
            }
        }
    
        void displayAccountDetails() {
            System.out.println("Account Number: " + accountNumber);
            System.out.println("Account Holder: " + accountHolderName);
            System.out.println("Balance: " + balance);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            BankAccount account1 = new BankAccount("A101", "Rahul", 5000);
    
            account1.deposit(1000);
            account1.withdraw(1500);
    
            account1.displayAccountDetails();
        }
    }
    

    This example shows how a constructor helps create a valid bank account object with required initial data.

    Real-World Example: Product Constructor

    In an e-commerce application, a Product object should contain product name, price, and stock quantity. A constructor can initialize these properties when the product object is created.

    
    class Product {
    
        String productName;
        double price;
        int stockQuantity;
    
        Product(String name, double productPrice, int stock) {
            productName = name;
    
            if (productPrice >= 0) {
                price = productPrice;
            } else {
                price = 0;
            }
    
            if (stock >= 0) {
                stockQuantity = stock;
            } else {
                stockQuantity = 0;
            }
        }
    
        void displayProduct() {
            System.out.println("Product Name: " + productName);
            System.out.println("Price: " + price);
            System.out.println("Stock Quantity: " + stockQuantity);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Product product1 = new Product("Mouse", 799.50, 25);
    
            product1.displayProduct();
        }
    }
    

    Here, the constructor initializes product details and prevents invalid price or stock values.

    Real-World Example: Student Management System

    In a student management system, constructors can make student object creation easier and more reliable. Instead of assigning each property separately, we can provide student details directly when creating the object.

    Object Constructor Call Initialized Values
    student1 Student("Rahul", 101, 85) name = Rahul, rollNumber = 101, marks = 85
    student2 Student("Ayesha", 102, 92) name = Ayesha, rollNumber = 102, marks = 92
    student3 Student("John", 103, 76) name = John, rollNumber = 103, marks = 76

    Advantages of Constructors

    Constructors provide many benefits in Object-Oriented Programming. They make object creation cleaner, safer, and more meaningful.

    Benefits of Constructors

    • Constructors initialize objects automatically.
    • They reduce repeated initialization code.
    • They ensure required data is provided during object creation.
    • They help objects start in a valid state.
    • They keep initialization logic inside the class.
    • They improve code readability and maintainability.
    • They can apply validation before assigning values.
    • They support flexible object creation through overloading.
    • They help implement encapsulation by controlling initialization.
    • They make real-world object modeling easier.

    Common Mistakes Beginners Make

    Beginners often face confusion while learning constructors. Understanding common mistakes helps avoid errors and improves object-oriented design.

    Common Mistakes

    • Thinking constructor is a normal method.
    • Forgetting that constructor runs automatically.
    • Not initializing required properties.
    • Writing too much unrelated logic inside constructor.
    • Not validating input values.
    • Confusing constructor parameters with object properties.
    • Creating too many overloaded constructors unnecessarily.
    • Using unclear parameter names.

    Better Approach

    • Use constructor mainly for object initialization.
    • Keep constructor logic simple and meaningful.
    • Initialize all required properties properly.
    • Use validation for important values.
    • Use clear parameter names.
    • Use constructor overloading only when useful.
    • Use methods for actions after object creation.
    • Design constructors according to object requirements.

    Constructor Best Practices

    A good constructor should create a valid and usable object. It should not become too complex or perform too many unrelated tasks.

    Best Practices for Constructors

    • Use constructors to initialize required object data.
    • Keep constructors short and focused.
    • Use meaningful parameter names.
    • Validate important input values before assigning them.
    • Avoid writing unrelated business operations inside constructors.
    • Do not create too many constructors without a clear reason.
    • Use default values when suitable.
    • Protect sensitive data using private properties and controlled methods.
    • Make sure the object is usable immediately after construction.
    • Use constructor overloading to support meaningful object creation options.

    How to Identify Constructor Requirements

    When designing a class, ask what information is required to create a valid object. These required values are usually good candidates for constructor parameters.

    CONSTRUCTOR DESIGN RULE
    Required Initial Data becomes Constructor Parameters

    For example, consider the following requirement:

    "A student record must have a name, roll number, and course at the time of admission."

    From this requirement, the constructor can accept:

    • studentName
    • studentRollNumber
    • studentCourse
    
    Student(String studentName, int studentRollNumber, String studentCourse) {
        name = studentName;
        rollNumber = studentRollNumber;
        course = studentCourse;
    }
    

    Mini Practice Activity

    Try to identify suitable constructor parameters for the following classes. This exercise will help you understand how constructors are designed in real-world applications.

    Class Required Constructor Parameters Reason
    Student name, rollNumber, course A student record needs identity and course details.
    BankAccount accountNumber, holderName, initialBalance A bank account should start with account details.
    Product productName, price, stockQuantity A product should have basic sale and stock details.
    Book title, author, isbn A book should have identity and author information.
    Vehicle vehicleNumber, brand, model A vehicle should have identification and model details.
    Employee employeeId, name, department An employee record should start with identity and department.

    Frequently Asked Questions

    1. What is a constructor in OOP?

    A constructor is a special method or class member that runs automatically when an object is created. It is mainly used to initialize object properties.

    2. Why do we use constructors?

    Constructors are used to give initial values to objects, reduce repeated code, and ensure that objects start in a valid and meaningful state.

    3. Is constructor the same as method?

    No. A constructor initializes an object and runs automatically during object creation. A method performs an action and is usually called manually after the object is created.

    4. Can a constructor have parameters?

    Yes. A constructor can have parameters. A constructor with parameters is called a parameterized constructor. It allows objects to be initialized with custom values.

    5. What is a default constructor?

    A default constructor is a constructor with no parameters. It can initialize an object with default values.

    6. What is constructor overloading?

    Constructor overloading means creating multiple constructors in the same class with different parameter lists. It allows objects to be created in different ways.

    7. Can a constructor return a value?

    In many class-based languages such as Java, a constructor does not have a return type and does not return a value like a normal method. Its purpose is to initialize the object.

    8. Can we write validation inside a constructor?

    Yes. Constructors can validate input values before assigning them to properties. This helps protect the object from invalid initial data.

    9. What happens if we do not write a constructor?

    In some programming languages, a default constructor may be provided automatically if no constructor is written. However, the exact behavior depends on the programming language.

    10. Should constructors contain complex logic?

    Usually, constructors should be simple and focused on initialization. Complex business operations should be placed in separate methods.

    Summary

    A constructor is an important concept in Object-Oriented Programming. It is used to initialize an object when the object is created. Constructors help assign initial values to object properties and ensure that the object starts in a valid state.

    Constructors can be default constructors, parameterized constructors, copy constructors, or private constructors depending on the language and design requirement. Constructor overloading allows multiple ways to create objects from the same class.

    A good constructor should be simple, clear, and focused on initialization. It should initialize required properties, validate important values, and help create objects that are ready to use immediately.

    Key Takeaway

    A constructor is a special class member that runs automatically when an object is created. Its main purpose is to initialize object properties and make sure the object starts with valid and meaningful data.