এক কনস্ট্রাক্টর মেথডের মতোই কিন্তু এটি ক্লাসের অবজেক্ট তৈরি করার সময় আহ্বান করা হয়। এটি সাধারণত ক্লাসের ইনস্ট্যান্স ভেরিয়েবল ইনিশিয়ালাইজ করার জন্য ব্যবহৃত হয়। কনস্ট্রাক্টরের নাম ক্লাসের নামের সাথে মিলে থাকে এবং এর কোনো রিটার্ন টাইপ নেই।
কনস্ট্রাক্টর দুটি ধরনের: প্যারামিটারাইজড কনস্ট্রাক্টর এবং নো-আর্গ কনস্ট্রাক্টর।
প্যারামিটারাইজড কনস্ট্রাক্টর
এক প্যারামিটারাইজড কনস্ট্রাক্টর প্যারামিটার গ্রহণ করে যাদি ইনস্ট্যান্স ভেরিয়েবল ইনিশিয়ালাইজ করা যায়। এর মাধ্যমে ক্লাস ইনস্ট্যান্টিয়েট করার সময় ডাইনামিকভাবে ভিন্ন ভ্যালু দিয়ে ইনিশিয়ালাইজ করা সম্ভব।
উদাহরণ
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 StudentData() {
this(null, 0);
}
public StudentData(String name) {
this(name, 0);
}
public StudentData(int age) {
this(null, 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(" ");
System.out.println("Display method of constructor that accepts both values: ");
new StudentData(name, age).display();
System.out.println(" ");
System.out.println("Display method of constructor that accepts only name: ");
new StudentData(name).display();
System.out.println(" ");
System.out.println("Display method of constructor that accepts only age: ");
new StudentData(age).display();
System.out.println(" ");
System.out.println("Display method of default constructor: ");
new StudentData().display();
}
}
আউটপুট
Enter the name of the student: Krishna
Enter the age of the student: 22
Display method of constructor that accepts both values:
Name of the Student: Krishna
Age of the Student: 22
Display method of constructor that accepts only name:
Name of the Student: Krishna
Age of the Student: 0
Display method of constructor that accepts only age:
Name of the Student: null
Age of the Student: 22