How does inheritance work in Dart classes? Provide an example.
In Dart, inheritance is a fundamental concept in object-oriented programming that allows classes to inherit properties and behaviors from other classes. It enables the creation of a hierarchical relationship between classes, where a derived class inherits the characteristics of a base class and can add or modify its own specific features. Inheritance promotes code reuse, extensibility, and the organization of related classes.
Inheritance in Dart is implemented using the `extends` keyword, where a derived class extends a base class. The derived class, also known as a subclass or child class, inherits all the instance variables, methods, and getters/setters from the base class, also known as a superclass or parent class. This means that the derived class can access and use the inherited members as if they were defined within itself.
Here's an example that illustrates the concept of inheritance in Dart:
```
dart`class Vehicle {
String brand;
int year;
Vehicle(this.brand, this.year);
void honk() {
print("Honk honk!");
}
void displayInfo() {
print("Brand: $brand, Year: $year");
}
}
class Car extends Vehicle {
int numberOfDoors;
Car(String brand, int year, this.numberOfDoors) : super(brand, year);
void accelerate() {
print("The car is accelerating.");
}
}
void main() {
Car myCar = Car("Toyota", 2022, 4);
myCar.displayInfo(); // Output: Brand: Toyota, Year: 2022
myCar.honk(); // Output: Honk honk!
myCar.accelerate(); // Output: The car is accelerating.
print("Number of doors: ${myCar.numberOfDoors}"); // Output: Number of doors: 4
}`
```
In the example above, we have a `Vehicle` class as the base class, which has instance variables `brand` and `year`, as well as methods `honk()` and `displayInfo()`. The `Car` class is derived from the `Vehicle` class using the `extends` keyword. It adds its own instance variable `numberOfDoors` and a method `accelerate()`.
In the `main()` function, we create an instance of the `Car` class called `myCar`. We can see that `myCar` can access the inherited `brand` and `year` variables and methods from the `Vehicle` class. Additionally, `myCar` can invoke its own method `accelerate()` and access its specific variable `numberOfDoors`.
Through inheritance, the `Car` class inherits the properties and behaviors of the `Vehicle` class, allowing code reuse and promoting a hierarchical relationship between related classes. This facilitates code organization, reduces redundancy, and enables the creation of specialized classes that inherit and extend the functionality of more general classes.
In summary, inheritance in Dart provides a mechanism for classes to inherit and extend the properties and behaviors of other classes. It supports the principles of code reuse, extensibility, and organization in object-oriented programming.