Start Coding

Topics

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 enables code reuse and promotes the creation of hierarchical relationships between classes.

Basic Syntax

To implement inheritance in Dart, use the extends keyword. Here's the basic syntax:

class ChildClass extends ParentClass {
  // Child class members
}

How Inheritance Works

When a class inherits from another class, it gains access to all the non-private members of the parent class. This includes methods, properties, and constructors. The child class can then:

  • Use inherited members directly
  • Override inherited methods to provide custom implementations
  • Add new members specific to the child class

Example: Basic Inheritance

class Animal {
  void makeSound() {
    print('The animal makes a sound');
  }
}

class Dog extends Animal {
  @override
  void makeSound() {
    print('The dog barks');
  }

  void fetch() {
    print('The dog fetches the ball');
  }
}

void main() {
  var dog = Dog();
  dog.makeSound(); // Output: The dog barks
  dog.fetch(); // Output: The dog fetches the ball
}

In this example, Dog inherits from Animal. It overrides the makeSound() method and adds a new fetch() method.

Constructors and Inheritance

When working with constructors in inheritance, you may need to call the parent class constructor. Use the super keyword for this purpose:

class Person {
  String name;
  Person(this.name);
}

class Employee extends Person {
  int id;
  Employee(String name, this.id) : super(name);
}

void main() {
  var employee = Employee('John Doe', 1001);
  print('${employee.name} (ID: ${employee.id})');
}

Best Practices

  • Use inheritance to model "is-a" relationships
  • Avoid deep inheritance hierarchies; prefer composition when appropriate
  • Override methods judiciously, maintaining the expected behavior of the parent class
  • Utilize the @override annotation for clarity and to catch errors

Related Concepts

To fully grasp inheritance in Dart, it's beneficial to understand these related concepts:

Mastering inheritance is crucial for writing efficient, maintainable Dart code. It allows you to create robust class hierarchies and promote code reuse across your applications.