এক কনস্ট্রাক্টর মেথডের মতোই কিন্তু এটি ক্লাসের অবজেক্ট তৈরি করার সময় আহ্বান করা হয়। এটি সাধারণত ক্লাসের ইনস্ট্যান্স ভেরিয়েবল ইনিশিয়ালাইজ করার জন্য ব্যবহৃত হয়। কনস্ট্রাক্টরের নাম ক্লাসের নামের সাথে মিলে থাকে এবং এর কোনো রিটার্ন টাইপ নেই।
কনস্ট্রাক্টর দুটি ধরনের: প্যারামিটারাইজড কনস্ট্রাক্টর এবং নো-আর্গ কনস্ট্রাক্টর। প্যারামিটারাইজড কনস্ট্রাক্টর প্যারামিটার গ্রহণ করে।
এক কনস্ট্রাক্টরর মূল উদ্দেশ্য হলো ক্লাসের ইনস্ট্যান্স ভেরিয়েবল ইনিশিয়ালাইজ করা। প্যারামিটারাইজড কনস্ট্রাক্টর ব্যবহার করে, আপনি ইনস্ট্যান্টিয়েশনের সময় নির্দিষ্ট ভ্যালু দিয়ে ইনস্ট্যান্স ভেরিয়েবল ডাইনামিকভাবে ইনিশিয়ালাইজ করতে পারেন।
public class Sample {
int i;
public Sample(int i) {
this.i = i;
}
}
উদাহরণ
নিচের উদাহরণে Student ক্লাসে দুটি প্রাইভেট ভেরিয়েবল age ও name আছে। মেইন মেথড থেকে প্যারামিটারাইজড কনস্ট্রাক্টর দিয়ে ক্লাস ভেরিয়েবল ইনস্ট্যান্টিয়েট করা হয়েছে।
import java.util.Scanner;
public class StudentData {
private String name;
private int age;
public StudentData(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name of the Student: " + this.name);
System.out.println("Age of the Student: " + this.age);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
System.out.println(" ");
new StudentData(name, age).display();
}
}
আউটপুট
Enter the name of the student: Sundar
Enter the age of the student: 20
Name of the Student: Sundar
Age of the Student: 20