Table of contents
In Dart, concrete classes are like ready-made tools with specific functions. They're already built and ready to use. But sometimes, we might not want to think about all the specific details of how they work. Instead, we just want to focus on what they can do without worrying about how they do it.
So, even though concrete classes have specific implementations, Dart allows us to use them in a way that hides those details.
Treating concrete classes as abstract in Dart means we can use them without needing to understand all the technical details of how they're built or how they function internally. We just focus on what they can do for us.
Example:
// Define a base class Animal
class Animal {
void makeSound() { // Method to make a generic sound
print('Some generic sound');
}
void eat() { // Method to eat
print('Eating...');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('Bark! Bark!');
}
void fetch() { // Additional method specific to Dog for fetching
print('Fetching the ball');
}
}
void main() {
// Creating instances of Animal and Dog
Animal animal = Animal();
Dog dog = Dog();
// Calling methods of the Animal class
animal.makeSound(); // Output: Some generic sound
animal.eat(); // Output: Eating...
// Calling methods of the Dog class
dog.makeSound(); // Output: Bark! Bark!
dog.eat(); // Output: Eating...
dog.fetch(); // Output: Fetching the ball
Benefits of Treating Concrete Classes as Abstract:
Flexibility: Allows for flexible code design and adaptation to changing requirements.
Modularity: Promotes modular code architecture by abstracting concrete class implementations.
Code Reusability: Enhances code reuse and promotes polymorphism by using concrete classes interchangeably.