Question #73EasyDart Basics

What is Object Oriented Programming in Dart: Inheritance ?

#dart

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

dart
void 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

dart
class 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

RuleDetail
Single inheritanceDart only supports
text
extends
one class
text
super
Access parent members
text
@override
Required annotation for overriding
Abstract methodsMust be overridden in subclass
ConstructorMust call
text
super()
if parent has required params
MultipleUse
text
implements
+
text
with
for multiple inheritance-like behavior

Tip: Use inheritance for "is-a" relationships (Car is-a Vehicle). Use mixins / composition for "has-a" relationships.