Inheritance and Extending Classes
Explore how to create subclasses in Dart using inheritance, establish "IS A" relationships with the extends keyword, and customize behavior by overriding methods. Understand abstract and sealed classes and learn how to safely initialize parent class data with super constructors.
Now that we are familiar with objects and classes, let us discuss inheritance.
The IS A relationship
Inheritance is a core concept of object-oriented programming. We use it to create a new class from an existing class. The new class inherits the properties and methods of the existing class. The class that inherits the members is known as the subclass. The class we inherit from is known as the superclass. In Dart, every class is implicitly a subclass of the Object class.
We use inheritance when we identify an "IS A" relationship between objects.
Look at these examples of the "IS A" relationship:
A circle is a shape. (Subclass: Circle, Superclass: Shape)
Dart is a programming language. (Subclass: Dart, Superclass: Programming Language)
A car is a vehicle. (Subclass: Car, Superclass: Vehicle)
While inheritance is powerful, we must use it only for true specialization. If a relationship is better described as "HAS A", we should prefer composition. For example, a car has an engine. We do not make the car a subclass of the engine. Instead, we include an engine object as an instance variable inside the car class.
Syntax for extending a class
Extending a class means taking an existing class and absorbing all of its data and behaviors into a new class. This ...