Answer
Overview
Inheritance allows a class (child/subclass) to inherit properties and methods from another class (parent/superclass), enabling code reuse and extending functionality.
Basic Inheritance
dart// Parent class (superclass) class Vehicle { String brand; int year; double _speed = 0; Vehicle(this.brand, this.year); void accelerate(double amount) { _speed += amount; print('$brand accelerating to $_speed km/h'); } void brake() { _speed = 0; print('$brand stopped'); } double get speed => _speed; String toString() => '$brand ($year)'; } // Child class (subclass) class Car extends Vehicle { int doors; String fuelType; Car(String brand, int year, this.doors, this.fuelType) : super(brand, year); // Call parent constructor void honk() => print('$brand: Beep beep!'); // Override parent method void accelerate(double amount) { super.accelerate(amount); // Call parent's method print('Car-specific: gear shifting...'); } } class ElectricCar extends Car { int batteryLevel; ElectricCar(String brand, int year) : batteryLevel = 100, super(brand, year, 4, 'Electric'); void charge() { batteryLevel = 100; print('$brand fully charged!'); } void accelerate(double amount) { if (batteryLevel > 10) { super.accelerate(amount); batteryLevel -= 5; } else { print('Low battery — cannot accelerate!'); } } }
Using Inherited Classes
dartvoid main() { final car = Car('Toyota', 2023, 4, 'Petrol'); car.accelerate(60); // Inherited + overridden car.honk(); // Car-specific car.brake(); // Inherited from Vehicle final tesla = ElectricCar('Tesla', 2024); tesla.accelerate(100); // ElectricCar override print(tesla.batteryLevel); // 95 tesla.charge(); }
super Keyword
dartclass Child extends Parent { void greet() { super.greet(); // Call parent's greet() first print('Child greeting'); } Child(String name) : super(name); // Call parent constructor }
Inheritance Rules in Dart
| Rule | Detail |
|---|---|
| Single inheritance | Dart only supports text |
text | Access parent members |
text | Required annotation for overriding |
| Abstract methods | Must be overridden in subclass |
| Constructor | Must call text |
| Multiple | Use text text |
Tip: Use inheritance for "is-a" relationships (Car is-a Vehicle). Use mixins / composition for "has-a" relationships.