乐闻世界logo
搜索文章和话题

How to Implement Inheritance in Dart?

2024年7月18日 12:18

Implementing inheritance in Dart primarily involves the following steps:

  1. Define the Base Class: First, define a base class that provides common functionality. The base class can include properties (fields) and methods.
dart
class Vehicle { String make; int year; Vehicle(this.make, this.year); void start() { print('Vehicle started'); } }
  1. Define the Subclass: Then, define one or more subclasses to inherit properties and methods from the base class. Use the extends keyword followed by the base class name in the subclass definition.
dart
class Car extends Vehicle { int doors; Car(String make, int year, this.doors) : super(make, year); void honk() { print('Car horn honking!'); } }
  1. Override Methods: In the subclass, you can override methods from the base class to provide more specific implementations. Using the @override annotation clearly indicates that you are overriding a base class method.
dart
class 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.

标签:Dart