What is Parameterized constructor? with code

A parameterized constructor is a constructor that accepts one or more parameters. It allows you to initialize the instance variables of a class with specific values provided at the time of object creation. Parameterized constructors provide flexibility in object initialization by allowing different sets of values to be passed to create objects with different initial states.

Here's an example that demonstrates a parameterized constructor:

public class MyClass { private int value; // Parameterized constructor public MyClass(int value) { this.value = value; // Initialize instance variable with the provided value } }

In this example, the MyClass class has a parameterized constructor that accepts an int parameter named value. Inside the constructor, the value of the value parameter is assigned to the instance variable this.value.

Here's how you can use the parameterized constructor to create objects with different initial values:

csharp
MyClass obj1 = new MyClass(10); // Create obj1 with value 10 MyClass obj2 = new MyClass(20); // Create obj2 with value 20

In the above example, obj1 and obj2 are instances of the MyClass class created using the parameterized constructor. By providing different values to the constructor, you can initialize the value field of each object differently.

Parameterized constructors are useful when you want to create objects with specific initial states based on the values passed as parameters. They allow you to customize the initialization process and set object properties or variables according to specific requirements.

It's important to note that a class can have multiple constructors, including both parameterized and non-parameterized constructors, allowing you to provide different options for object initialization.


 

Post a Comment

Previous Post Next Post