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
Child Class: Car
Demonstrating Inheritance

Now in the main function, let’s instantiate a Car object and observe how it utilizes both inherited methods and its specialized method.

void main() {
    Car myCar = Car('Toyota', 120.0, 4); // Output: Calling Vehicle constructor
    // Inherited method from Vehicle
    myCar.move(); // Output: Toyota moves at 120.0 mph.
    // Car's own method
    myCar.specs(); // Output: I am a Toyota and I have 4 wheels.
}
Overriding Methods in Inheritance
Lesson Summary

Today, we've dissected inheritance in Dart, by using ‘Vehicle’ and ‘Car’ classes to demonstrate inheritance in action, highlighting how child classes inherit and potentially modify properties and methods from parent classes, alonside the significance of the extends and super keywords in establishing and facilitating this inheritance.

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