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.
To implement inheritance in Dart, use the extends
keyword. Here's the basic syntax:
class ChildClass extends ParentClass {
// Child class members
}
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:
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.
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})');
}
@override
annotation for clarity and to catch errorsTo 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.