What is an Abstract Class in Dart?
An abstract class in Dart is a class that cannot be instantiated directly. It serves as a blueprint for other classes, allowing you to define methods and properties that must be implemented by subclasses. Abstract classes are useful for defining a common interface and shared behavior for a group of related classes, promoting code reuse and enforcing a contract for subclasses.
1. Defining an Abstract Class
To define an abstract class in Dart, you use the abstract
keyword before the class declaration. An abstract class can contain both abstract methods (methods without an implementation) and concrete methods (methods with an implementation).
Example of an Abstract Class
abstract class Animal {
String name;
// Abstract method
void makeSound();
// Concrete method
void displayInfo() {
print('Animal name: $name');
}
}
In this example, we define an abstract class Animal
with an abstract method makeSound
and a concrete method displayInfo
. The abstract method does not have an implementation, meaning that any subclass must provide its own implementation of this method.
2. Subclassing an Abstract Class
When a class extends an abstract class, it must implement all of the abstract methods defined in the abstract class. This ensures that the subclass adheres to the contract established by the abstract class.
Example of Subclassing an Abstract Class
class Dog extends Animal {
Dog(this.name);
@override
void makeSound() {
print('$name barks.');
}
}
class Cat extends Animal {
Cat(this.name);
@override
void makeSound() {
print('$name meows.');
}
}
void main() {
Dog myDog = Dog('Buddy');
myDog.displayInfo(); // Output: Animal name: Buddy
myDog.makeSound(); // Output: Buddy barks.
Cat myCat = Cat('Whiskers');
myCat.displayInfo(); // Output: Animal name: Whiskers
myCat.makeSound(); // Output: Whiskers meows.
}
In this example, the Dog
and Cat
classes extend the abstract class Animal
and provide their own implementations of the makeSound
method. When we create instances of Dog
and Cat
, we can call both the displayInfo
and makeSound
methods.
3. Benefits of Using Abstract Classes
- Code Reusability: Abstract classes allow you to define common behavior that can be reused across multiple subclasses.
- Enforcing a Contract: By defining abstract methods, you ensure that all subclasses implement specific functionality, promoting consistency.
- Polymorphism: Abstract classes enable polymorphism, allowing you to treat different subclasses as instances of the abstract class.
4. Conclusion
Abstract classes in Dart are a powerful feature that allows you to define a common interface and shared behavior for related classes. By using abstract classes, you can promote code reuse, enforce contracts for subclasses, and leverage polymorphism in your applications. Understanding how to define and use abstract classes effectively is essential for building robust and maintainable Dart applications.