Inheritance is a fundamental concept in object-oriented programming that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). Dart supports single inheritance, meaning a subclass can inherit from only one superclass. Let's explore how inheritance works in Dart:
class SuperClass {
// Superclass members
}
class SubClass extends SuperClass {
// Subclass members
}
class Animal {
String name;
Animal(this.name);
}
class Dog extends Animal {
String breed;
Dog(String name, this.breed) : super(name);
}
class Animal {
void speak() {
print('Animal speaks');
}
}
class Dog extends Animal {
@override
void speak() {
print('Dog barks');
}
}
You can access superclass members (fields, methods) from the subclass using the super keyword.
class Animal {
void speak() {
print('Animal speaks');
}
}
class Dog extends Animal {
@override
void speak() {
super.speak(); // Call superclass method
print('Dog barks');
}
}