In Dart, implementing inheritance is a relatively straightforward process. By using the keyword extends, a class can inherit properties and methods from another class. This is a fundamental concept in object-oriented programming, aimed at improving code reusability and maintainability.
Example Explanation:
Suppose we have a base class Vehicle that represents all types of vehicles. This class has some basic properties such as name and speed, and a method displayInformation to display vehicle information.
dartclass Vehicle { String name; double speed; Vehicle(this.name, this.speed); void displayInformation() { print("Vehicle Name: $name"); print("Speed: $speed km/h"); } }
Now, if we want to create a specific type of Vehicle, such as Car, we can make the Car class inherit from the Vehicle class. This way, the Car class will inherit all properties and methods from Vehicle and can also add specific properties or methods.
dartclass Car extends Vehicle { int numberOfDoors; Car(String name, double speed, this.numberOfDoors) : super(name, speed); void displayInformation() { super.displayInformation(); print("Number of Doors: $numberOfDoors"); } }
In this example, the Car class inherits from the Vehicle class using the extends keyword. We add a new property numberOfDoors to the Car class. Additionally, we override the displayInformation method to include the functionality of displaying the number of doors. Note that we use the @override annotation to indicate that we are overriding the base class method, and we call the parent class method using super.displayInformation().
Benefits of Inheritance:
- Code Reusability: We can reuse the code from the
Vehicleclass through inheritance, without having to repeat the same code in each vehicle class. - Extensibility: Inheritance makes it easy to extend existing functionality by simply adding or overriding the required features.
- Maintainability: With inheritance, modifications to common functionality only need to be made once in the base class, and all derived classes automatically inherit these changes, reducing the complexity and risk of errors in maintenance.
Through this approach, Dart supports class inheritance, enabling developers to build more complex and diverse system architectures.