Inheritance

Inheritance

About

  • Inheritance enables code reuse through parent-child relationships.
  • Dart uses single inheritance (one superclass per class).
  • Supports method overriding and super calls.
  • Fundamental to object-oriented design.

Main Topics

  1. Basic Inheritance

    • Definition: Creating child classes with extends.
    • Example:
      class Animal {
        void eat() => print('Eating');
      }
      class Dog extends Animal {} // Inherits eat()
  2. Super Constructor

    • Definition: Initializing parent class.
    • Example:
      class Animal {
        String name;
        Animal(this.name);
      }
      class Dog extends Animal {
        Dog(super.name); // Super constructor
      }
  3. Method Overriding

    • Definition: Customizing inherited behavior.
    • Example:
      class Dog extends Animal {
        @override
        void eat() => print('Dog eating');
      }
  4. Super Calls

    • Definition: Accessing parent implementations.
    • Example:
      void eat() {
        super.eat(); // Parent's eat()
        print('Additional behavior');
      }

How to Use

  • Extend: Use extends for basic inheritance
  • Initialize: Chain constructors with super()
  • Override: Annotate with @override
  • Access: Use super for parent members

How It Works

  • Hierarchy: Single chain of superclasses
  • Lookup: Child methods shadow parent methods
  • Construction: Parent initialized before child
  • Polymorphism: Child instances as parent types

Example Session:

void main() {
  Animal myDog = Dog(); // Polymorphism
  myDog.eat(); // Calls overridden method
}

Conclusion

Inheritance in Dart provides controlled code reuse while maintaining type safety through method overriding and super calls, forming the backbone of object-oriented design patterns.