Dart Inheritance
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →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
@overrideannotation for clarity and to catch errors
Related Concepts
To fully grasp inheritance in Dart, it's beneficial to understand these related concepts:
- Dart Classes - The foundation for creating objects and implementing inheritance
- Dart Interfaces - Another way to define a contract for classes
- Dart Abstract Classes - Classes that can't be instantiated and may contain abstract methods
- Dart Mixins - A way to reuse code from multiple classes
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.