Abstract Class এবং Interface হল অবজেক্ট-ওরিয়েন্টেড প্রোগ্রামিংয়ের (OOP) দুটি গুরুত্বপূর্ণ ধারণা। এগুলি সফটওয়্যার ডিজাইনে নমনীয়তা এবং পুনঃব্যবহারযোগ্যতা বাড়াতে সহায়ক। নিচে প্রতিটির ব্যবহার এবং উদাহরণ সহ বিস্তারিত আলোচনা করা হলো।
1. Abstract Class
Abstract Class একটি ক্লাস যা এক বা একাধিক অ্যাবস্ট্রাক্ট মেথড (abstract methods) ধারণ করে। অ্যাবস্ট্রাক্ট মেথডগুলি এমন মেথড যা সুপার ক্লাসে সংজ্ঞায়িত করা হয় কিন্তু সাব ক্লাসে অবশ্যই প্রয়োগ করতে হয়। এটি সাব ক্লাসের জন্য একটি ব্লুপ্রিন্ট হিসেবে কাজ করে।
উদাহরণ:
abstract class Animal {
String name;
Animal(this.name); // Constructor
// Abstract method
void speak(); // No implementation, must be implemented by subclasses
}
class Dog extends Animal {
Dog(String name) : super(name); // Calling super constructor
@override
void speak() {
print("$name barks.");
}
}
class Cat extends Animal {
Cat(String name) : super(name); // Calling super constructor
@override
void speak() {
print("$name meows.");
}
}
void main() {
Animal myDog = Dog('Buddy');
Animal myCat = Cat('Whiskers');
myDog.speak(); // Output: Buddy barks.
myCat.speak(); // Output: Whiskers meows.
}
2. Interface
Dart এ একটি ক্লাস স্বাভাবিকভাবে একটি ইন্টারফেস হিসেবে কাজ করে। এটি শুধুমাত্র মেথড ঘোষণা করতে পারে এবং কোনো ডেটা বা কনস্ট্রাক্টর থাকতে পারে না। ইন্টারফেস ব্যবহার করে আপনি বিভিন্ন ক্লাসের মধ্যে সাধারণ আচরণ সংজ্ঞায়িত করতে পারেন।
উদাহরণ:
// Defining an interface
class CanFly {
void fly(); // Abstract method
}
class Bird implements CanFly {
String name;
Bird(this.name);
@override
void fly() {
print("$name is flying.");
}
}
class Airplane implements CanFly {
String model;
Airplane(this.model);
@override
void fly() {
print("$model is flying.");
}
}
void main() {
CanFly myBird = Bird('Sparrow');
CanFly myPlane = Airplane('Boeing 747');
myBird.fly(); // Output: Sparrow is flying.
myPlane.fly(); // Output: Boeing 747 is flying.
}
3. Key Differences between Abstract Classes and Interfaces
| Feature | Abstract Class | Interface |
|---|---|---|
| Implementation | Can provide default implementation | Cannot provide implementation |
| Inheritance | A class can extend only one abstract class | A class can implement multiple interfaces |
| Constructor | Can have constructors | Cannot have constructors |
| Member Types | Can have fields, methods, and getters/setters | Only method declarations |
| Use Case | When you want to provide common base functionality | When you want to enforce a contract |
Read more