持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情
抽象类
在 Dart 中, 如果有很多通用接口时,通常可以把这些方法定义为抽象方法,抽象方法必须放在抽象类中,抽象类用关键字 abstract 修饰
注意:
- 抽象类不能实例化
- 抽象类中的抽象方法必须被子类实现,抽象类中已经实现的方法,子类可以不重写
abstract class Person {
sayHI();
}
class Boy extends Person {
@override
sayHI() {}
}
class Girl extends Person {
@override
sayHI() {}
}
隐式接口
- 在 Dart 中,关于接口的声明没有具体关键字,类似
interface、protocol...。默认情况下,定义的每一个类都相当于一个接口文件,被称为隐式接口 - 在实际开发中,通常将用于给别人实现的类定义为抽象类
- 关于隐式接口是的使用是通过关键字
implements修饰。当一个类被当作接口文件使用时,那么实现这个接口的类必须实现这个接口文件中所有的方法
abstract class Hobby {
void run();
void playFootball();
}
abstract class Study {
void studyChinese();
void studyEnlish();
}
// Student 实现了 Hobby, Study 的所有的接口
class Student implements Hobby, Study {
@override
void run() {
print("重写 run");
}
@override
void playFootball() {
print("重写 playFootball");
}
@override
void studyChinese() {
print("重写 studyChinese");
}
@override
void studyEnlish() {
print("重写 studyEnlish");
}
}
void main(List<String> args) {
final stu = Student();
stu.run();
stu.playFootball();
stu.studyChinese();
stu.studyEnlish();
}
log:
重写 run
重写 playFootball
重写 studyChinese
重写 studyEnlish
Mixin 混入
在上述中,通过 implements 实现隐式接口时,无论这个接口文件中的接口是否已经实现过,接口文件中所有的方法都必须被重新实现。但在某些情况下,一个类可能希望直接复用之前类的原有实现,这种情况,可以使用 Mixin 混入的方式
-
实现混入使用关键字
mixin修饰 -
使用混入时,使用关键字
with进行混入mixin Hobby { void run() { print("run"); } void playFootball() { print("playFootball"); } } mixin Study { void studyChinese() { print("studyChinese"); } void studyEnlish() { print("studyEnlish"); } } // 使用 Mixin 混入的方式 class Student with Hobby, Study { @override void run() { print("重写 run"); } @override void studyChinese() { print("重写 studyChinese"); } } void main(List<String> args) { final stu = Student(); stu.run(); stu.playFootball(); stu.studyChinese(); stu.studyEnlish(); } log: 重写 run playFootball 重写 studyChinese studyEnlish -
使用
with实现多继承,必须要先有extends然后才能使用with实现mixins操作class Person { void run() { print("Person -run"); } } mixin Hobby { void run() { print("Hobby - run"); } void playFootball() { print("Hobby -playFootball"); } } mixin Sport { void run() { print("Sport -run"); } void playFootball() { print("Sport -playFootball"); } void swimming() { print("Sport -swimming"); } } class Student extends Person with Hobby, Sport {} void main(List<String> args) { final stu = Student(); stu.run(); stu.playFootball(); stu.swimming(); } log: Sport -run Sport -playFootball Sport -swimming由于,继承的顺序中,Sport 是在最后,所以就会去调用 Sport 中的方法。修改这个继承顺序,那么就会看最后的那个类,再去执行最后那个类的方法
修改继承顺序,将 Sport 和 Hobby 换个位置
class Student extends Person with Sport, Hobby {} void main(List<String> args) { final stu = Student(); stu.run(); stu.playFootball(); stu.swimming(); } log: Hobby - run Hobby -playFootball Sport -swimming