KnowledgeBoat Logo
|

Computer Applications

What is a parameterized constructor ? How is it useful ?

Java Constructors

3 Likes

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.

Answered By

2 Likes


Related Questions