Back to the 2020 paper

Module III: Basics of Web Programming

20207m

What is a constructor in Java? How many types of constructors are there in Java? Explain with examples.

Worked SolutionAI Assisted

Answer: Constructors in Java — Types and Examples

1. What is a Constructor in Java?

A Constructor in Java is a special member method invoked automatically at runtime when an instance (object) of a class is created using the new keyword. Its primary purpose is to initialize the newly created object's state (instance variables) and allocate necessary resources.

+-------------------+      new Student("Rohan", 101)      +-----------------------------+
|    Client Code    | ----------------------------------> |      Constructor Invoked    |
+-------------------+                                     | Sets name = "Rohan", id=101 |
                                                          +-----------------------------+

Essential Rules for Constructors:

  1. Name Rule: The constructor name must be identical to the class name.
  2. No Return Type: It must not have any explicit return type (not even void).
  3. Modifiers: Cannot be abstract, static, final, or synchronized. Access modifiers (public, protected, private, default) are permitted.

2. Types of Constructors in Java

                               +-----------------------------+
                               |     TYPES OF CONSTRUCTORS   |
                               +--------------+--------------+
                                              |
                     +------------------------+------------------------+
                     |                        |                        |
                     v                        v                        v
           +--------------------+   +--------------------+   +--------------------+
           |  Default / No-Arg  |   |   Parameterized    |   |  Copy Constructor  |
           |    Constructor     |   |    Constructor     |   |   (Object Copy)    |
           +--------------------+   +--------------------+   +--------------------+

A. Default / No-Argument Constructor

  • If no constructor is defined in a class, the Java compiler automatically inserts a default no-argument constructor that initializes instance variables to default values (0, null, false).
  • Programmers can also explicitly define a no-arg constructor to provide default custom values.
class Student {
    String name;
    int rollNo;

    // Explicit No-Argument Constructor
    Student() {
        this.name = "Unknown";
        this.rollNo = 0;
        System.out.println("Default/No-Arg Constructor called");
    }
}

B. Parameterized Constructor

  • A constructor that accepts one or more arguments to initialize instance variables with custom values at the time of object instantiation.
class Student {
    String name;
    int rollNo;

    // Parameterized Constructor
    Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
        System.out.println("Parameterized Constructor called");
    }
}

C. Copy Constructor

  • Java does not have a built-in copy constructor like C++, but programmers create copy constructors by passing an existing object of the same class to initialize a new object with identical attributes.
class Student {
    String name;
    int rollNo;

    // Copy Constructor
    Student(Student other) {
        this.name = other.name;
        this.rollNo = other.rollNo;
        System.out.println("Copy Constructor called");
    }
}

3. Comprehensive Code Example (Constructor Overloading & Chaining)

class Book {
    String title;
    String author;
    double price;

    // 1. No-argument Constructor
    Book() {
        this("Untitled", "Anonymous", 0.0); // Constructor chaining using this()
    }

    // 2. Parameterized Constructor (2 parameters)
    Book(String title, String author) {
        this(title, author, 199.99);
    }

    // 3. Parameterized Constructor (3 parameters)
    Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    // 4. Copy Constructor
    Book(Book other) {
        this.title = other.title;
        this.author = other.author;
        this.price = other.price;
    }

    void display() {
        System.out.println("Title: " + title + " | Author: " + author + " | Price: Rs." + price);
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        Book b1 = new Book();
        Book b2 = new Book("Java: Complete Reference", "Herbert Schildt");
        Book b3 = new Book("Web Technologies", "Achyut Godbole", 550.0);
        Book b4 = new Book(b3); // Copy constructor

        System.out.println("
--- Book Details ---");
        b1.display();
        b2.display();
        b3.display();
        b4.display();
    }
}

Output:

--- Book Details ---
Title: Untitled | Author: Anonymous | Price: Rs.0.0
Title: Java: Complete Reference | Author: Herbert Schildt | Price: Rs.199.99
Title: Web Technologies | Author: Achyut Godbole | Price: Rs.550.0
Title: Web Technologies | Author: Achyut Godbole | Price: Rs.550.0

Similar questions