Understanding Inheritance in Dart Classes

Introduction to Inheritance

Welcome back to our exploration of Object-Oriented Programming (OOP) in Dart. In this session, we'll delve into Inheritance, a core concept that elevates code reusability and efficiency.

What is Inheritance?

Inheritance in Object-Oriented Programming (OOP) allows a new class, known as the Child class, to inherit properties and methods from another class, termed the Parent class. This principle not only facilitates code reusability but also organizes classes into a hierarchical structure.

To understand inheritance better, we're going to dive into a practical example where we use Vehicle as the parent class and Car as the child class. This will help us see how child classes can adopt attributes and behaviors from parent classes, while also introducing or modifying features to meet their specific needs. In Dart, the relationship between parent and child classes is established using the extends keyword.

Parent Class: Vehicle

We begin by defining a Vehicle class that includes common properties and methods applicable to all types of vehicles.

Dart
// Vehicle class - Parent class
class Vehicle {
    String name; // Vehicle name
    double speed; // Maximum speed

    // Constructor
    Vehicle(this.name, this.speed) {
      print('Calling Vehicle constructor');
    }
  
    void move() {
        print('$name moves at $speed mph.');
    }
}

Child Class: Car

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal