Follow Us
Select Medium / माध्यम चुनें:
Eng (English) Hindi (हिन्दी)
ICSE • Class X • Information Technology • Ch 4
Estimated Time: 45 Mins
Study Progress: In Progress

Constructors

Comprehensive pedagogical guide to Constructors in Java. Covers initialization mechanics, default vs parameterized constructors, constructor overloading, the 'this' keyword, constructor chaining, copy constructors, constructor vs method comparisons, and complete ICSE board programming solutions.

Why This Chapter Matters

Comprehensive pedagogical guide to Constructors in Java. Covers initialization mechanics, default vs parameterized constructors, constructor overloading, the 'this' keyword, constructor chaining, copy constructors, constructor vs method comparisons, and complete ICSE board programming solutions.

Chapter Roadmap & Progression

1 1. Constructor Definition, Architec...
2 2. Types of Constructors: Default,...
3 3. The 'this' Keyword: Variable Sha...
4 4. Constructor Overloading & Copy C...
5 5. Constructor vs Member Method: Th...
6 6. Destruction and the Garbage Coll...
7 7. Complete ICSE Board Program: Boo...
8 8. Complete ICSE Board Program: Rai...

Complete Concept Guide (100% Curriculum Coverage)

1. Constructor Definition, Architectural Role & Invariants

Constructor Essentials
The Vital Role of Constructors in Object Lifecycle:

In Java, when the new operator allocates contiguous Heap memory for an object, the object's instance fields initially hold default language values (e.g., 0, 0.0, null, false). A Constructor is a specialized member block designed specifically to initialize those data members to meaningful, valid business states before the object reference is returned to the program.

The Three Non-Negotiable Syntactic Invariants:
  1. Exact Name Parity: The constructor MUST have the exact same identifier as the enclosing class, matching capitalization identically (e.g., in class Account, the constructor must be Account()).
  2. Zero Return Type: A constructor has NO return type—not even void.
    Warning: If you write public void Account() { ... }, the Java compiler will NOT report an error; instead, it will compile it as a regular member method named Account and will NOT invoke it upon new Account()!
  3. Automatic Invocation: A constructor cannot be called explicitly like an ordinary method (e.g., obj.Account(); is invalid syntax). It is invoked automatically during the execution of the new operator.

2. Types of Constructors: Default, Non-Parameterized & Parameterized

Constructor Hierarchy
Taxonomy of Constructors in Java:
Constructor ClassificationDefinition & CharacteristicsSyntax & Example
Default Constructor An invisible, parameter-less constructor synthesized automatically by the Java compiler ONLY when the class contains zero explicitly defined constructors. It initializes numeric fields to 0, references to null, and booleans to false. // Generated in bytecode:
public Student() { super(); }
Non-Parameterized Constructor An explicit constructor coded by the programmer that accepts zero arguments. It assigns predetermined default values defined by business logic (e.g., balance = 500.0). public Book() {
  title = "Untitled";
  price = 0.0;
}
Parameterized Constructor A constructor defined with a formal parameter list. It accepts incoming arguments during object creation (new Book("Java", 450.0);) to initialize instance variables to custom initial states. public Book(String t, double p) {
  title = t;
  price = p;
}

3. The 'this' Keyword: Variable Shadowing & Constructor Chaining

The 'this' Keyword
Resolving Variable Shadowing:

When formal parameter names in a constructor are identical to instance variable names, the local parameters 'shadow' (hide) the instance variables. The this keyword is an implicit reference variable pointing to the currently executing object instance on the Heap.

public class Employee {
    private int empId;
    private String name;

    // Parameter names match instance variable names exactly:
    public Employee(int empId, String name) {
        this.empId = empId; // 'this.empId' refers to instance field; 'empId' refers to parameter
        this.name = name;
    }
}
Constructor Chaining via this():

Constructor chaining is the technique of invoking one constructor from another constructor within the same class using this(...). This prevents code duplication when multiple overloaded constructors perform overlapping initialization.

Mandatory Rule: The call to this(...) MUST be the very first executable statement in the constructor body.

4. Constructor Overloading & Copy Constructors

Overloading & Copying
Constructor Overloading:

Like methods, constructors can be overloaded by providing multiple constructor definitions with different parameter counts or parameter types within the same class. This empowers client code to construct objects flexibly depending on available input data.

The Copy Constructor Paradigm:

A Copy Constructor is a parameterized constructor that accepts an existing object of the SAME class as its parameter and initializes the new object with duplicates of the fields of the passed object:

public class Rectangle {
    private int length, breadth;

    // Normal parameterized constructor
    public Rectangle(int l, int b) {
        length = l; breadth = b;
    }

    // Copy Constructor
    public Rectangle(Rectangle existing) {
        this.length = existing.length;
        this.breadth = existing.breadth;
    }
}
// Usage: Rectangle r1 = new Rectangle(10, 20);
//        Rectangle r2 = new Rectangle(r1); // r2 is an independent clone!

5. Constructor vs Member Method: The Definitive Comparative Matrix

Comparative Analysis
Constructor vs Member Method:
Comparative ParameterConstructorMember Method
Identifier / NameMUST be exactly identical to the enclosing Class Name.Can be any valid Java identifier (e.g., calculate).
Return TypeHas NO return type (not even void).MUST have a declared return type (data type or void).
Invocation TriggerInvoked automatically upon new instantiation.Invoked explicitly using the dot operator (obj.method()).
Execution FrequencyExecutes exactly once per object creation.Can be invoked multiple times throughout the object's life.
Primary ObjectiveTo allocate memory and initialize instance variables.To execute operational logic and process data.
Default ProvisionSynthesized automatically by compiler if none defined.Never provided automatically by the compiler.

6. Destruction and the Garbage Collection Lifecycle

Object Destruction
Automatic Cleanup vs finalize():

In languages like C++, every constructor has a corresponding Destructor (e.g., ~ClassName()) to manually release allocated Heap memory. In Java, destructors do NOT exist because memory management is completely automated by the JVM Garbage Collector.

An object becomes eligible for garbage collection when it is no longer reachable from any live Stack reference. Java historically provided a protected void finalize() method invoked before an object is swept from memory, though modern Java encourages explicit resource release via try-with-resources.

7. Complete ICSE Board Program: BookFair Discount Class

Board Class Implementation
Model Program 1: ICSE Classic 'BookFair' Class
import java.util.Scanner;

public class BookFair {
    // Instance Variables
    private String bname;
    private double price;

    // 1. Default / Non-Parameterized Constructor
    public BookFair() {
        bname = "";
        price = 0.0;
    }

    // 2. Member Method to input data
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Book Name: ");
        bname = in.nextLine();
        System.out.print("Enter Book Price: Rs. ");
        price = in.nextDouble();
    }

    // 3. Member Method to calculate discounted price
    public void calculate() {
        double discountPercent;
        if (price <= 1000.0) {
            discountPercent = 2.0;
        } else if (price <= 3000.0) {
            discountPercent = 10.0;
        } else {
            discountPercent = 15.0;
        }

        double discountAmount = (price * discountPercent) / 100.0;
        price = price - discountAmount;
    }

    // 4. Member Method to display details
    public void display() {
        System.out.println("--------------------------------");
        System.out.println("BOOK FAIR INVOICE");
        System.out.println("Book Name          : " + bname);
        System.out.println("Price After Discount: Rs. " + price);
        System.out.println("--------------------------------");
    }

    public static void main(String[] args) {
        BookFair book = new BookFair(); // Constructor executes here!
        book.input();
        book.calculate();
        book.display();
    }
}

8. Complete ICSE Board Program: RailwayTicket Reservation Class

Board Class Implementation
Model Program 2: ICSE 'RailwayTicket' Reservation System
import java.util.Scanner;

public class RailwayTicket {
    private String name;
    private String coach;
    private long mobno;
    private int amt;
    private double totalamt;

    // Parameterized Constructor
    public RailwayTicket(String name, String coach, long mobno, int amt) {
        this.name = name;
        this.coach = coach;
        this.mobno = mobno;
        this.amt = amt;
        this.totalamt = 0.0;
    }

    public void compute() {
        int surcharge = 0;
        if (coach.equalsIgnoreCase("First_AC")) {
            surcharge = 700;
        } else if (coach.equalsIgnoreCase("Second_AC")) {
            surcharge = 500;
        } else if (coach.equalsIgnoreCase("Third_AC")) {
            surcharge = 250;
        } else if (coach.equalsIgnoreCase("Sleeper")) {
            surcharge = 0;
        }
        totalamt = amt + surcharge;
    }

    public void display() {
        System.out.println("=================================");
        System.out.println("INDIAN RAILWAYS RESERVATION SLIP");
        System.out.println("Passenger Name : " + name);
        System.out.println("Coach Selected : " + coach);
        System.out.println("Mobile Number  : " + mobno);
        System.out.println("Base Amount    : Rs. " + amt);
        System.out.println("Total Payable  : Rs. " + totalamt);
        System.out.println("=================================");
    }

    public static void main(String[] args) {
        RailwayTicket ticket = new RailwayTicket("Vikram Singhania", "First_AC", 9876543210L, 1850);
        ticket.compute();
        ticket.display();
    }
}

Common Misconceptions & Examiner Traps

Common Misconception

Adding a void return type to a constructor definition

Scientific Reality & Correction

Constructors MUST NOT have any return type. Adding 'void' converts it into an ordinary member method.

Common Misconception

Placing this(...) constructor chaining statement on line 2 or later

Scientific Reality & Correction

The call to 'this(...)' MUST be the very first statement inside the constructor body.

Common Misconception

Assuming the compiler provides a default constructor when a parameterized one is written

Scientific Reality & Correction

Defining any parameterized constructor disables the automatic default constructor. You must explicitly write a zero-argument constructor if needed.

Common Misconception

Trying to invoke a constructor using the dot operator on an existing object

Scientific Reality & Correction

Constructors cannot be called via the dot operator (e.g., 'obj.Student();' is illegal). They are invoked solely via 'new'.

Architectural Blueprint : Constructors

ICSE Class 10 Java : Constructor Architecture & Object Initialization Lifecycle 1. Special Properties • Name Parity: Exact same name as Class • No Return Type: NOT even void! • Auto Invocation: Invoked via 'new' operator • Primary Goal: Initialize instance state in Heap 2. Constructor Types • Default Constructor: Auto-created by JVM if none coded. • Non-Parameterized: Explicitly coded with 0 parameters. • Parameterized: Accepts arguments for custom state. • Copy Constructor: Duplicates state of another object. 3. The 'this' Keyword • Current Instance Ref: Refers to invoking object in Heap. • Variable Shadowing: this.name = name; resolves clash. • Constructor Chaining: this(args); calls sibling constructor. MUST be line 1 in constructor! 4. Constructor vs Method • Return Type: Constructor: None | Method: Required • Invocation: Constructor: via 'new' | Method: via dot • Overloading: Multiple constructors with distinct signatures. Enables flexible instantiation. Crucial ICSE Constructor Invariant Principles • Loss of Default Constructor: If a programmer defines ANY constructor (even parameterized), the compiler removes the default constructor. • Constructor Return Type Myth: If a return type (even void) is added, Java treats it as a normal method, NOT a constructor! • Invocation Frequency: A constructor is executed exactly ONCE per object creation during the new lifecycle.

Chapter Summary & 10 Key Takeaways

Takeaway 1
A Constructor is a special member function having the exact same name as the class, dedicated to initializing the newly instantiated object's instance variables.
Takeaway 2
Constructors possess no return type whatsoever—not even `void`. Specifying a return type turns it into an ordinary member method.
Takeaway 3
Constructors are automatically invoked by the Java runtime when an object is instantiated using the `new` operator.
Takeaway 4
A Default Constructor takes no parameters and is automatically provided by the Java compiler ONLY IF no constructors are explicitly defined by the programmer.
Takeaway 5
Defining any custom constructor (parameterized or non-parameterized) causes the compiler to withdraw its automatic default constructor.
Takeaway 6
Parameterized constructors allow external arguments to be passed during object creation, ensuring objects can be initialized with distinct, dynamic initial states.
Takeaway 7
Constructor Overloading allows a class to define multiple constructors with varying parameter counts or types to support diverse instantiation workflows.
Takeaway 8
The `this` reference variable points to the current invoking instance and resolves variable shadowing when parameter names match instance variable names.
Takeaway 9
Constructor chaining is achieved using `this(...)` to invoke a sibling constructor within the same class; `this(...)` MUST be the very first statement.
Takeaway 10
Unlike member methods which can be invoked repeatedly via the dot operator throughout an object's life, a constructor executes only ONCE per object creation.

Check Your Understanding (Diagnostic Practice Questions)

Diagnostic questions testing core conceptual clarity. Answers are hidden initially — solve each problem first, then click to reveal the step-by-step verified solution.

1
Define a Constructor in Java. State two special features that distinguish it from regular methods.
Reveal Answer & Explanation
Answer: A Constructor is a specialized member function within a class designed to initialize the newly allocated instance variables of an object when it is instantiated. Two distinguishing features: 1. It shares the exact same name as the class. 2. It has NO return type (not even 'void'). 3. It cannot be invoked via the dot operator; it executes automatically when the 'new' keyword creates an object in memory.
2
What is a Default Constructor? Under what specific condition does the Java compiler NOT provide one?
Reveal Answer & Explanation
Answer: A Default Constructor is a zero-argument constructor generated automatically by the Java compiler during compilation if and only if the class contains no explicit constructor definitions. It assigns default zero-equivalent values to all instance fields. The compiler does NOT provide a default constructor if the programmer defines ANY constructor in the class (whether parameterized or non-parameterized).
3
What is variable shadowing, and how does the 'this' keyword resolve it within constructors?
Reveal Answer & Explanation
Answer: Variable shadowing occurs when formal parameters in a constructor share the identical identifier names as the class's instance variables; within the constructor scope, the parameter shadows (takes precedence over) the instance variable. The 'this' keyword is an implicit reference variable pointing to the current executing object instance on the Heap. Prefixing the instance variable with 'this.' (e.g., 'this.name = name;') explicitly directs the compiler to assign the local parameter to the Heap object's instance variable.
4
Explain Constructor Overloading with a real-world programming scenario.
Reveal Answer & Explanation
Answer: Constructor Overloading occurs when a class declares multiple constructors with the same class name but differing parameter lists (different number, types, or order of parameters). For example, a 'Student' class may provide a non-parameterized constructor 'Student()' that assigns default values, alongside a parameterized constructor 'Student(String name, int rollNo)' for cases where complete student information is immediately known at object instantiation time.
5
What is Constructor Chaining? State the mandatory syntactic rule when using this().
Reveal Answer & Explanation
Answer: Constructor Chaining is the practice where one constructor invokes another overloaded constructor within the same class using the keyword 'this(...)'. This avoids redundant code across multiple constructors. The mandatory syntactic rule is that the call to 'this(...)' MUST be the very first executable statement in the calling constructor's body; placing it on any subsequent line causes a compile-time error.
6
What happens if a programmer mistakenly specifies a return type (like void) for a constructor?
Reveal Answer & Explanation
Answer: If a return type (such as 'void' or 'int') is specified in a constructor declaration (e.g., 'public void Student()'), the Java compiler no longer treats it as a constructor. Instead, it compiles it as a regular member method that happens to share the class name. Consequently, it will NOT execute during 'new Student()', leaving instance variables initialized only to language default values.
7
What is a Copy Constructor in Java? How is it implemented?
Reveal Answer & Explanation
Answer: A Copy Constructor is a specialized constructor that creates a new object by copying the state of an already existing object of the same class. It accepts an object of its own class as a formal parameter (e.g., 'public Point(Point p)') and copies the field values from the parameter object into the newly instantiated object ('this.x = p.x; this.y = p.y;'), yielding an independent duplicate.
8
Why does Java not feature 'Destructors' like C++?
Reveal Answer & Explanation
Answer: Java does not have destructors because it features automatic Garbage Collection (GC). In languages with manual memory management (like C++), destructors must be explicitly written to release Heap memory. In Java, the JVM runtime continuously monitors object references and automatically deallocates Heap memory occupied by unreferenced objects, rendering manual destructors unnecessary.
Finished Studying This Chapter?
READY TO PRACTICE?

Timed CBT Practice Tests (Exam Simulator)

Put your concepts to the test with official curriculum-aligned Foundation and Advanced practice tests. Get instant accuracy scores, time metrics, and step-by-step verified explanations.