ICSE Class 10 Computer Applications Question 18 of 19

Constructors — Question 18

Back to all questions
18
Question

Question 18

What is a parameterized constructor ? How is it useful ?

Answer

Parameterized constructors are the constructors that receive parameters and initialize objects with received values. For example:

class XYZ
{
    private int i; 
    private float j;

    XYZ(int a, float b)     //parameterized constructor
    {	
        i = a ;
        j = b;
    }
    :
    //other  members
    :
}

Parameterized constructors are useful in the following ways:

  1. Control over object creation — By writing our own constructors, we can control how objects of our class are created and initialised. It ensures initialising member variables to specific values and executing certain initialisation logic before the object is used.
  2. Parameter validation — We can prevent runtime errors and bugs by validating input parameters and ensuring only valid objects are created.