一、继承
lass Animal {
// 抽象属性
String name = "" ;
// 抽象方法
void eat(){
print("吃了");
}
}
class Dog extends Animal {
@override
void eat() {
// TODO: implement eat
super.eat();
}
}
- Dart中的继承使用extends关键字
- Dart只支持单继承,可通过Mixin横向复用代码,实现类似多继承的效果
- 子类中使用super来访问父类。
二、抽象类
抽象类(Abstract Class)是一种特殊的类,不能被直接实例化,通过 abstract 关键字声明,用于定义子类的通用接口规范。
abstract class Animal {
abstract String name; // 抽象属性
void eat(); // 抽象方法
void sleep() { // 具体方法
print('$name is sleeping');
}
}
class Dog extends Animal {
@override
String name; // 必须实现抽象属性
Dog(this.name);
@override
void eat() { // 必须实现抽象方法
print('$name eats bones');
}
}
void main() {
Animal dog = Dog('Buddy');
dog.eat(); // 输出 "Buddy eats bones"
dog.sleep(); // 输出 "Buddy is sleeping"
}
- 抽象类(abstract class)的核心作用之一就是通过抽象成员(属性/方法)强制子类实现特定的行为或数据,形成一种“不可妥协的契约”。
三、implements
implements 表示一个类"承诺实现"另一个类或抽象类的所有公开成员(方法和属性)。简单来说,就是让你的类符合某个"标准"或"契约"。
3.1、基本语法
class 子类 implements 父类/接口 {
// 必须实现父类/接口中所有的公开方法和属性
}
3.2、 与 extends 的区别

截屏2025-03-28 14.19.51.png
3.3、基本用法示例
- 示例1:普通类作为接口
class Bird {
void fly() => print('鸟儿在飞');
}
// RobotBird 实现 Bird 接口
class RobotBird implements Bird {
@override
void fly() {
print('机器鸟用螺旋桨飞');
}
}
- 示例2:实现抽象类接口
// 普通类也可以作为接口
class Bird {
void fly() => print('鸟儿在飞');
}
// RobotBird 实现 Bird 接口
class RobotBird implements Bird {
@override
void fly() {
print('机器鸟用螺旋桨飞');
}
}
- 示例3:实现多个接口
abstract class Flyable {
void fly();
}
abstract class Swimmable {
void swim();
}
// Duck 实现两个接口
class Duck implements Flyable, Swimmable {
@override
void fly() => print('鸭子在飞');
@override
void swim() => print('鸭子在游泳');
}
四、混合继承(Mixins)
Mixin 是一种特殊的类,它包含了一些可复用的方法和属性,可以被其他类"混入"使用。与继承不同,一个类可以混入多个 Mixin。
mixin Flyable {
void fly() {
print('正在飞行');
}
}
class Bird with Flyable {
// 自动获得 fly() 方法
}
void main() {
var bird = Bird();
bird.fly(); // 输出: 正在飞行
}
mixin Flyable {
void fly() => print('飞行中');
}
mixin Swimmable {
void swim() => print('游泳中');
}
class Duck with Flyable, Swimmable {
// 获得 fly() 和 swim() 方法
}
void main() {
var duck = Duck();
duck.fly(); // 输出: 飞行中
duck.swim(); // 输出: 游泳中
}
abstract class Animal {
String get name;
}
mixin Flyable {
void fly() => print('$name 正在飞');
}
class Bird extends Animal with Flyable {
@override
final String name;
Bird(this.name);
}
void main() {
var bird = Bird('小鸟');
bird.fly(); // 输出: 小鸟 正在飞
}
五、总结
5.1、快速决策流程图
需要代码复用吗?
├─ 是 → 需要多重继承吗?
│ ├─ 是 → 使用 with(Mixins)
│ └─ 否 → 需要强制子类实现规范吗?
│ ├─ 是 → 使用 abstract class + extends
│ └─ 否 → 使用普通 extends
└─ 否 → 需要接口约束吗?
├─ 是 → 使用 implements
└─ 否 → 直接写普通类
5.2、四大特性对比表(含具体场景)

截屏2025-03-28 14.42.09.png