কনস্ট্রাক্টর ওভারলোডিং (Constructor Overloading):
কনস্ট্রাক্টর ওভারলোডিং বলতে বুঝায় একটি ক্লাসের একাধিক কন্সট্রাক্টর থাকবে যাদের আলাদা আলাদা প্যারামিটার থাকবে, যাতে করে প্রত্যেকটি কন্সট্রাক্টর দ্বারা বিভিন্ন রকম অবজেক্ট তৈরি করা যায় ।
class MyClass {
private int value;
private String name;
// Constructor with no parameters
public MyClass() {
System.out.println(“No argument Constructor”);
this.value = 0;
this.name = “Default Name”;
}
// Constructor with one parameter
public MyClass(int value) {
System.out.println(“Constructor with int parameter”);
this.value = value;
this.name = “Default Name”;
}
// Constructor with two parameters
public MyClass(int value, String name) {
System.out.println(“Constructor with int and String parameters”);
this.value = value;
this.name = name;
}
public void display() {
System.out.println(“Value: ” + value + “, Name: ” + name);
}
}
class Main{
public static void main(String[] args) {
MyClass obj1 = new MyClass(); // Default Constructor
MyClass obj2 = new MyClass(10); // Constructor with int parameter
MyClass obj3 = new MyClass(20, “Custom Name”); // Constructor with int and String parameters
obj1.display();
obj2.display();
obj3.display();
}
}
উপরের উদাহরণে ভিন্ন প্যারামিটার যুক্ত তিনটি কনস্ট্রাকটর ডিফাইন করা হয়েছে। এখানে কন্সট্রাক্টর গুলোর প্যারামিটারের সংখ্যা এবং টাইপের উপর ভিত্তি করে ওভারলোড করা হয়েছে ।
উদাহরণ : https://dotnetfiddle.net/QNyuSV
using System;
public class MyClass {
private int value;
private string name;
// Constructor with no parameters
public MyClass() {
Console.WriteLine(“No argument Constructor”);
this.value = 0;
this.name = “Default Name”;
}
// Constructor with one parameter
public MyClass(int value) {
Console.WriteLine(“Constructor with int parameter”);
this.value = value;
this.name = “Default Name”;
}
// Constructor with two parameters
public MyClass(int value, string name) {
Console.WriteLine(“Constructor with int and String parameters”);
this.value = value;
this.name = name;
}
public void Display() {
Console.WriteLine(“Value: ” + value + “, Name: ” + name);
}
}
public class MainClass {
public static void Main(string[] args) {
MyClass obj1 = new MyClass(); // Default Constructor
MyClass obj2 = new MyClass(10); // Constructor with int parameter
MyClass obj3 = new MyClass(20, “Custom Name”); // Constructor with int and String parameters
obj1.Display();
obj2.Display();
obj3.Display();
}
}
Output:
//Output (আউটপুট) No argument Constructor Constructor with int parameter Constructor with int and String parameters Value: 0, Name: Default Name Value: 10, Name: Default Name Value: 20, Name: Custom Name