定义

  • Dart 接口是一种[father::Dart 抽象类],它定义了一个类应该具有的方法和属性,但没有具体的实现。

接口继承

Dart 支持接口之间的继承,通过 extends 关键字可以继承一个或多个父接口。

abstract class Flyable {
  void fly();
}
 
abstract class Animal {
  void eat();
}
 
class Bird implements Animal, Flyable {
  @override
  void eat() {
    print('Bird is eating');
  }
 
  @override
  void fly() {
    print('Bird is flying');
  }
}

示例

// 定义一个接口
abstract class Animal {
  void makeSound();
}
 
// 实现接口
class Dog implements Animal {
  @override
  void makeSound() {
    print('Woof Woof');
  }
}
 
class Cat implements Animal {
  @override
  void makeSound() {
    print('Meow');
  }
}
 
void main() {
  Animal dog = Dog();
  dog.makeSound(); // 输出: Woof Woof
  
  Animal cat = Cat();
  cat.makeSound(); // 输出: Meow
}