Implementing inheritance in Dart primarily involves the following steps:
- Define the Base Class: First, define a base class that provides common functionality. The base class can include properties (fields) and methods.
dartclass Vehicle { String make; int year; Vehicle(this.make, this.year); void start() { print('Vehicle started'); } }
- Define the Subclass: Then, define one or more subclasses to inherit properties and methods from the base class. Use the
extendskeyword followed by the base class name in the subclass definition.
dartclass Car extends Vehicle { int doors; Car(String make, int year, this.doors) : super(make, year); void honk() { print('Car horn honking!'); } }
- Override Methods: In the subclass, you can override methods from the base class to provide more specific implementations. Using the
@overrideannotation clearly indicates that you are overriding a base class method.
dartclass Car extends Vehicle { int doors; Car(String make, int year, this.doors) : super(make, year); void start() { super.start(); // Call the base class's start method print('Car engine started'); } void honk() { print('Car horn honking!'); } }
By following these steps, you can flexibly implement inheritance relationships between classes in Dart, enabling code reuse and creating more hierarchical and professional object structures.