一.繼承extends
-
dart里的繼承是單繼承,即只能有一個父類。
- 子類會繼承父類所有非私有屬性和方法。
二.抽象類abstract
- 不能被實例化,只能被子類繼承。
- 可以在抽象類中定義抽象方法和普通方法,抽象方法不能有實現(xiàn),且子類必須重寫該方法。
abstract class Example {
/// getter屬性
int get calculate;
/// 抽象方法
void methodOne();
/// 普通方法
void methodTwo() {
print('methodTwo');
}
}
三.接口實現(xiàn)implements
- 當(dāng)一個類被
implements時,子類需要重寫該類的所有屬性和方法。
class AnotherExample implements Example {
@override
int get calculate => 1;
@override
void methodOne() {
print('methodOne');
}
@override
void methodTwo() {
print('methodTwo');
}
}
abstract class InterfaceOne {
void one();
}
class InterfaceTwo {
void two() {}
}
class Interface implements InterfaceOne, InterfaceTwo {
@override
void one() {}
@override
void two() {}
}
四.混合mixin
- 不能有構(gòu)造函數(shù)。
- 一個類可以混合多個
mixin類。
-
mixin不能繼承。
mixin Breathing {
void swim() => print('Breathing');
}
mixin Walking {
void walk() => print('Walking');
}
mixin Coding {
void code() => print('Hello world');
}
abstract class Human with Breathing {
}
class Developer extends Human with Walking, Coding {
}
void main() {
final developer = Developer();
developer..walk()..code()..swim();
}
- 可以使用關(guān)鍵字
on將mixin限制為某個特定類。
mixin BallUtil in Widget {
double ballVolume(double radius) {
return 4 / 3 * 3.14 * pow(radius, 3);
}
}
class VolleyballPitch extends StatelessWidget with BallUtils {
// code...
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。