In Dart, inheritance allows a class to reuse the properties and methods of another class, promoting code reusability and a clear hierarchical structure. The class that inherits is called the subclass (or child class), and the class being inherited from is called the superclass (or parent class). Dart uses the extends keyword for single inheritance.
For example:
class Vehicle {
void start() {
print('Vehicle started');
}
}
class Car extends Vehicle {
void honk() {
print('Car horn sounds');
}
}
void main() {
var myCar = Car();
myCar.start(); // inherited from Vehicle
myCar.honk(); // defined in Car
}
Here, Car inherits the start() method from Vehicle. This means we don’t need to rewrite common functionality for every subclass.
I’ve applied inheritance in Flutter projects when creating different UI components that share some common behavior. For example, I created a base Button class with common styling and functionality, and then extended it to PrimaryButton and SecondaryButton with their own specific features.
One challenge I faced was understanding method overriding and the use of the super keyword when the subclass needs to extend or modify the behavior of the superclass method. A limitation in Dart is that it only supports single inheritance, so for cases where multiple behaviors are needed, we use mixins or interfaces as alternatives to combine functionality from multiple sources.
