Skip to content

OOP: Inheritance and Polymorphism

Inheritance

Inheritance allows a class to inherit properties and methods from another class.

dart
class Animal {
  String name;
  int age;
  
  Animal(this.name, this.age);
  
  void makeSound() {
    print('Some sound');
  }
  
  void eat() {
    print('$name is eating');
  }
}

class Dog extends Animal {
  String breed;
  
  Dog(String name, int age, this.breed) : super(name, age);
  
  @override
  void makeSound() {
    print('Woof! Woof!');
  }
  
  void fetch() {
    print('$name is fetching');
  }
}

void main() {
  var dog = Dog('Buddy', 3, 'Golden Retriever');
  dog.makeSound();  // Woof! Woof!
  dog.eat();        // Buddy is eating
  dog.fetch();      // Buddy is fetching
}

Polymorphism

dart
void animalSound(Animal animal) {
  animal.makeSound();
}

void main() {
  Animal animal = Animal('Generic', 5);
  Dog dog = Dog('Buddy', 3, 'Labrador');
  
  animalSound(animal);  // Some sound
  animalSound(dog);     // Woof! Woof!
}

Method Overriding

dart
class Shape {
  double area() => 0;
}

class Circle extends Shape {
  double radius;
  
  Circle(this.radius);
  
  @override
  double area() => 3.14159 * radius * radius;
}

class Rectangle extends Shape {
  double width, height;
  
  Rectangle(this.width, this.height);
  
  @override
  double area() => width * height;
}

Super Keyword

dart
class Vehicle {
  String brand;
  
  Vehicle(this.brand);
  
  void info() {
    print('Brand: $brand');
  }
}

class Car extends Vehicle {
  int doors;
  
  Car(String brand, this.doors) : super(brand);
  
  @override
  void info() {
    super.info();  // Call parent method
    print('Doors: $doors');
  }
}

Next Steps

Content is for learning and research only.