Inheritance
Inheritance (উত্তরাধিকার) কি?
Inheritance বা উত্তরাধিকার হলো Object Oriented Programming (OOP)-এর একটি গুরুত্বপূর্ণ বৈশিষ্ট্য, যার মাধ্যমে একটি ক্লাস অন্য একটি ক্লাসের প্রপার্টি ও মেথড উত্তরাধিকারসূত্রে পায়। এটি কোড রিপিটিশন কমাতে সাহায্য করে।
📌 কখন ব্যবহার করব?
- যখন একাধিক ক্লাসের মধ্যে কমন (common) প্রপার্টি বা মেথড থাকে।
- কোডে রিইউজেবিলিটি এবং মেইন্টেইনযোগ্যতা বাড়াতে চাইলে।
- বাস্তব জীবনের সম্পর্ক মডেল করতে চাইলে (যেমন:
Teacher
এবংStudent
→ দুইজনেই মানুষ বা ব্যক্তিPerson
এর সাবক্লাস)।
🧪 কোড উদাহরণ বিশ্লেষণ
🔹 আগে: কোড রিপিটিশনের সমস্যা
class Student {
name: string;
age: number;
address: string;
constructor(name: string, age: number, address: string) {
this.name = name;
this.age = age;
this.address = address;
}
}
class Teacher {
name: string;
age: number;
address: string;
designation: string;
constructor(name: string, age: number, address: string, designation: string) {
this.name = name;
this.age = age;
this.address = address;
this.designation = designation;
}
}
🔍 উপরের দুই ক্লাসে name
, age
, এবং address
একই আছে। এটাকে আমরা রিপিটিশন বলতে পারি, যা ভালো প্র্যাকটিস নয়।
✅ পরে: Inheritance ব্যবহার করে কোড অপ্টিমাইজ
class Parent {
name: string;
age: number;
address: string;
constructor(name: string, age: number, address: string) {
this.name = name;
this.age = age;
this.address = address;
}
}
🔹 এখন Student2
ও Teacher2
এই Parent
ক্লাস থেকে ইনহেরিট করবে।
class Student2 extends Parent {
constructor(name: string, age: number, address: string) {
super(name, age, address); // Parent constructor call
}
}
class Teacher2 extends Parent {
designation: string;
constructor(name: string, age: number, address: string, designation: string) {
super(name, age, address); // Parent constructor call
this.designation = designation;
}
}
🔎 কেন super()
ব্যবহার করা হয়?
super()
হলো প্যারেন্ট ক্লাসের কনস্ট্রাক্টরকে কল করার মাধ্যম।- যখন কোনো সাবক্লাস তৈরি হয়, তখন প্যারেন্ট ক্লাসের ইনিশিয়ালাইজেশন
super()
দিয়ে করতে হয়।
🎯 কেন Inheritance দরকার?
কারণ | ব্যাখ্যা |
---|---|
🔁 Code Reusability | একবার কমন কোড লিখে বিভিন্ন সাবক্লাসে ব্যবহার করা যায় |
🧹 Less Redundancy | বারবার একই প্রপার্টি বা মেথড না লিখলেও চলে |
🛠️ Better Maintenance | কোড পরিবর্তন করতে হলে শুধু প্যারেন্ট ক্লাসেই করতে হয় |
🧠 Reflects Real World | বাস্তব জগতের জিনিসগুলোর সম্পর্ক মডেল করা সহজ (e.g., Employee extends Person ) |
🧾 সংক্ষেপে:
extends
দিয়ে ইনহেরিটেন্স করা হয়।super()
দিয়ে প্যারেন্ট কনস্ট্রাক্টর কল করা হয়।- কমন প্রপার্টি/মেথড প্যারেন্ট ক্লাসে রেখে কোড পুনঃব্যবহার করা যায়।
Last updated on