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:
- 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.
- 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
When a compiler can automatically generate a constructor if it is not defined then why is it considered that writing constructors for a class is a good practice ?
'Accessibility of a constructor greatly affects the scope and visibility of their class.' Elaborate this statement.
List some of the special properties of the constructor functions.
Design a class to represent a bank account. Include the following members:
Data members
- Name of the depositor
- Account number
- Type of account
- Balance amount in the account
Methods
- To assign initial values
- To deposit an amount
- To withdraw an amount after checking balance
- To display the name and balance
- Do write proper constructor functions