Abstract classes are a fundamental concept in Dart's object-oriented programming model. They serve as blueprints for other classes, defining a common interface without providing complete implementations.
An abstract class is a class that cannot be instantiated directly. It's designed to be subclassed, providing a common structure for related classes. Abstract classes can contain both abstract and concrete methods.
To define an abstract class in Dart, use the abstract
keyword before the class declaration:
abstract class Shape {
double area(); // Abstract method
void display() {
print('This is a shape.'); // Concrete method
}
}
Let's create a more comprehensive example to illustrate the use of abstract classes:
abstract class Animal {
String name;
Animal(this.name);
void makeSound(); // Abstract method
void introduce() {
print('I am a $name.');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
@override
void makeSound() {
print('Woof!');
}
}
class Cat extends Animal {
Cat(String name) : super(name);
@override
void makeSound() {
print('Meow!');
}
}
void main() {
var dog = Dog('Buddy');
var cat = Cat('Whiskers');
dog.introduce();
dog.makeSound();
cat.introduce();
cat.makeSound();
}
In this example, Animal
is an abstract class with both an abstract method (makeSound()
) and a concrete method (introduce()
). The Dog
and Cat
classes extend Animal
and provide implementations for the abstract method.
To deepen your understanding of Dart's object-oriented features, explore these related topics:
Abstract classes are a powerful tool in Dart for creating flexible and maintainable code structures. They provide a way to define common behaviors and enforce implementation in subclasses, promoting code reuse and consistency in your Dart projects.