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.
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.
Following the demonstration of the Car class, you might have noticed two pivotal keywords in action: extends and super.
-
extendsKeyword:- Used to establish a subclass (e.g.,
Car) that inherits properties and methods from a superclass (e.g.,Vehicle), theextendskeyword streamlines code reuse and maintenance. It signifies thatCaris a specialized version ofVehicle.
- Used to establish a subclass (e.g.,
-
superKeyword:- The
superkeyword in the subclass constructor calls the superclass's constructor, ensuring inherited properties (likenameandspeedfromVehicle) are initialized properly. This maintains the integrity of the inherited properties during object creation.
- The
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.
