一、繼承
lass Animal {
// 抽象屬性
String name = "" ;
// 抽象方法
void eat(){
print("吃了");
}
}
class Dog extends Animal {
@override
void eat() {
// TODO: implement eat
super.eat();
}
}
- Dart中的繼承使用extends關(guān)鍵字
- Dart只支持單繼承,可通過Mixin橫向復(fù)用代碼,實(shí)現(xiàn)類似多繼承的效果
- 子類中使用super來訪問父類。
二、抽象類
抽象類(Abstract Class)是一種特殊的類,不能被直接實(shí)例化,通過 abstract 關(guān)鍵字聲明,用于定義子類的通用接口規(guī)范。
abstract class Animal {
abstract String name; // 抽象屬性
void eat(); // 抽象方法
void sleep() { // 具體方法
print('$name is sleeping');
}
}
class Dog extends Animal {
@override
String name; // 必須實(shí)現(xiàn)抽象屬性
Dog(this.name);
@override
void eat() { // 必須實(shí)現(xiàn)抽象方法
print('$name eats bones');
}
}
void main() {
Animal dog = Dog('Buddy');
dog.eat(); // 輸出 "Buddy eats bones"
dog.sleep(); // 輸出 "Buddy is sleeping"
}
- 抽象類(abstract class)的核心作用之一就是通過抽象成員(屬性/方法)強(qiáng)制子類實(shí)現(xiàn)特定的行為或數(shù)據(jù),形成一種“不可妥協(xié)的契約”。
三、implements
implements 表示一個類"承諾實(shí)現(xiàn)"另一個類或抽象類的所有公開成員(方法和屬性)。簡單來說,就是讓你的類符合某個"標(biāo)準(zhǔn)"或"契約"。
3.1、基本語法
class 子類 implements 父類/接口 {
// 必須實(shí)現(xiàn)父類/接口中所有的公開方法和屬性
}
3.2、 與 extends 的區(qū)別

截屏2025-03-28 14.19.51.png
3.3、基本用法示例
- 示例1:普通類作為接口
class Bird {
void fly() => print('鳥兒在飛');
}
// RobotBird 實(shí)現(xiàn) Bird 接口
class RobotBird implements Bird {
@override
void fly() {
print('機(jī)器鳥用螺旋槳飛');
}
}
- 示例2:實(shí)現(xiàn)抽象類接口
// 普通類也可以作為接口
class Bird {
void fly() => print('鳥兒在飛');
}
// RobotBird 實(shí)現(xiàn) Bird 接口
class RobotBird implements Bird {
@override
void fly() {
print('機(jī)器鳥用螺旋槳飛');
}
}
- 示例3:實(shí)現(xiàn)多個接口
abstract class Flyable {
void fly();
}
abstract class Swimmable {
void swim();
}
// Duck 實(shí)現(xiàn)兩個接口
class Duck implements Flyable, Swimmable {
@override
void fly() => print('鴨子在飛');
@override
void swim() => print('鴨子在游泳');
}
四、混合繼承(Mixins)
Mixin 是一種特殊的類,它包含了一些可復(fù)用的方法和屬性,可以被其他類"混入"使用。與繼承不同,一個類可以混入多個 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(); // 輸出: 小鳥 正在飛
}
五、總結(jié)
5.1、快速決策流程圖
需要代碼復(fù)用嗎?
├─ 是 → 需要多重繼承嗎?
│ ├─ 是 → 使用 with(Mixins)
│ └─ 否 → 需要強(qiáng)制子類實(shí)現(xiàn)規(guī)范嗎?
│ ├─ 是 → 使用 abstract class + extends
│ └─ 否 → 使用普通 extends
└─ 否 → 需要接口約束嗎?
├─ 是 → 使用 implements
└─ 否 → 直接寫普通類
5.2、四大特性對比表(含具體場景)

截屏2025-03-28 14.42.09.png