Understand inheritance in Dart using programming and real-world examples.
Inheritance is a way for one class (called the child or subclass) to take properties and behaviors (methods) from another class (called the parent or superclass). It helps reuse code and create relationships between classes.
Think of a Vehicle as a general category. It has common things like wheels, speed, and the ability to move. A Car and a Bike are both Vehicles, but they have some special features too. So, Car and Bike inherit the common features of Vehicle but also add their own unique traits.
class Vehicle {
void move() {
print("Vehicle is moving");
}
}
class Car extends Vehicle {
void honk() {
print("Car is honking");
}
}
void main() {
Car myCar = Car();
myCar.move(); // Inherited method
myCar.honk(); // Car's own method
}
Here, Car inherits from Vehicle. It can use the move() method from Vehicle and also has its own honk() method.
You can change (override) the behavior of inherited methods.
class Vehicle {
void move() {
print("Vehicle is moving");
}
}
class Car extends Vehicle {
@override
void move() {
print("Car is moving fast");
}
}
void main() {
Car myCar = Car();
myCar.move(); // Output: Car is moving fast
}
The @override keyword tells Dart that we want to replace the move() method with a new one in Car.
Inheritance helps keep your code clean and organized by reusing common functionality. Instead of rewriting the same code in every class, you write it once in a parent class and inherit it.