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

Next, we extend the Vehicle class to create a Car class. The Car class inherits properties from Vehicle and adds a specific characteristic, the number of wheels.

Dart
// 'Car' class extending 'Vehicle' - Child class
class Car extends Vehicle {
    int wheels; // Additional property unique to Car

    Car(String name, double speed, this.wheels) : super(name, speed); // Calling Vehicle's constructor

    void specs() {
        print('I am a $name and I have $wheels wheels.');
    }
}

Following the demonstration of the Car class, you might have noticed two pivotal keywords in action: extends and super.

  • extends Keyword:

    • Used to establish a subclass (e.g., Car) that inherits properties and methods from a superclass (e.g., Vehicle), the extends keyword streamlines code reuse and maintenance. It signifies that Car is a specialized version of Vehicle.
  • super Keyword:

    • The super keyword in the subclass constructor calls the superclass's constructor, ensuring inherited properties (like name and speed from Vehicle) are initialized properly. This maintains the integrity of the inherited properties during object creation.

In essence, extends lets a subclass inherit from a superclass, while super initializes inherited properties correctly, facilitating effective code reuse and organization in Dart programs.

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