ডিফল্ট কনস্ট্রাক্টর (নো-আর্গ কনস্ট্রাক্টর)
এক নো-আর্গ কনস্ট্রাক্টর কোনো প্যারামিটার গ্রহণ করে না। এটি ক্লাস ভেরিয়েবলগুলকে তাদের ডিফল্ট ভ্যালুতে ইনস্ট্যান্টিয়েট করে (অবজেক্টের জন্য null, float/double-এর জন্য 0.0, Boolean-এর জন্য false, byte/short/int/long-এর জন্য 0)।
কনস্ট্রাক্টর এক্সপ্লিসিটলি আহ্বান করার প্রয়োজন নেই, এগুলো অবজেক্ট ইনস্ট্যান্টিয়েশনের সময় স্বয়ংক্রিয়ভাবে আহ্বান হয়।
মনে রাখার নিয়মাবলী
- কনস্ট্রাক্টরের কোনো রিটার্ন টাইপ নেই।
- কনস্ট্রাক্টরের নাম ক্লাসের নামের সাথে মিলে থাকতে হবে।
- কনস্ট্রাক্টর abstract, final, static বা synchronized হতে পারে না।
- কনস্ট্রাক্টরের সাথে public, protected, private অ্যাক্সেস স্পেসিফায়ার ব্যবহার করা যায়।
উদাহরণ
class NumberValue {
private int num;
public void display() {
System.out.println("The number is: " + num);
}
}
public class Demo {
public static void main(String[] args) {
NumberValue obj = new NumberValue();
obj.display();
}
}
আউটপুট
The number is: 0
উদাহরণ: ফাইনাল ফিল্ড সহ ডিফল্ট কনস্ট্রাক্টর
public class Student {
public final String name;
public final int age;
public Student() {
this.name = "Raju";
this.age = 20;
}
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[]) {
new Student().display();
}
}
আউটপুট
Name of the Student: Raju
Age of the Student: 20