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

Does Dart has a syntax for declaring interfaces?

1个答案

1

In Dart, there is no dedicated keyword for declaring interfaces; instead, every class implicitly defines an interface. This means you can treat any class as an interface, and other classes can implement it using the implements keyword. Additionally, if you only want to define partial behavior, you can use an abstract class to define one or more unimplemented methods, allowing other classes to implement these methods.

Example

Suppose we want an interface Vehicle that requires the drive method:

dart
// This is an abstract class, but in Dart it also defines a Vehicle interface abstract class Vehicle { void drive(); } // This is a class that implements the Vehicle interface class Car implements Vehicle { void drive() { print('Car is driving'); } } // This is another class that implements the Vehicle interface class Bicycle implements Vehicle { void drive() { print('Bicycle is riding'); } } void main() { var car = Car(); car.drive(); // Output: Car is driving var bike = Bicycle(); bike.drive(); // Output: Bicycle is riding }

In this example, we define an abstract class Vehicle that requires any class implementing it to have the drive method. Then we create two classes, Car and Bicycle, which both implement the Vehicle interface and provide their own implementation of the drive method. In Dart, this is a typical approach to interface-oriented programming.

2024年7月18日 20:16 回复

你的答案