Classes

Dart Inheritance

Class Inheritance

Dart inheritance uses extends with override methods.

Introduction to Dart Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In Dart, inheritance is achieved using the extends keyword. This allows one class (the subclass) to inherit the fields and methods of another class (the superclass), enabling code reusability and the creation of a hierarchical class structure.

Using the Extends Keyword

The extends keyword in Dart is used to create a subclass from an existing class. The subclass inherits all the properties and methods of the superclass, which can then be used or overridden to provide specific functionality.

Here is a basic example to illustrate:

Overriding Methods

In Dart, a subclass can override a method of its superclass to provide a new implementation. This is done using the @override annotation, which improves readability and ensures that the method is indeed overriding a superclass method.

Consider the following example where we override the eat method:

Benefits of Inheritance

Inheritance in Dart offers several advantages:

  • Code Reusability: Common functionality can be defined in a single class and reused by multiple subclasses.
  • Modularity: Changes in the superclass can be automatically reflected in subclasses.
  • Polymorphism: Subclasses can define their own unique behaviors while sharing common structure.