extents 和 implements都能实现抽象类定义规范,应该怎么选择呢?
- 如果要复用抽象类里的非抽象方法则选择
extents
- 如果单纯当标准定义规范的话用
implements
extents实现抽象类
/*
abstract抽象类 用于定于标准。不能实例化对象,抽象方法子类必须实现
*/
abstract class Animal {
eat(); //抽象类
printInfo() {
//非抽象方法,子类不必实现
print("Animal");
}
}
class Dog extends Animal {
@override
eat() {
print("小狗在吃骨头");
}
}
class Cat extends Animal {
@override
eat() {
print("小狗在吃骨头");
}
}
void main() {
//多态,父类指针指向子类对象
Animal dog = Dog();
dog.eat();
}
implements实现抽象类
abstract class Animal {
eat(); //抽象类
}
class Dog implements Animal {
@override
eat() {
print("小狗在吃骨头");
}
}
class Cat implements Animal {
@override
eat() {
print("小狗在吃骨头");
}
}
void main() {
//多态,父类指针指向子类对象
Animal dog = Dog();
dog.eat();
runApp(const MyApp());
}
一个类实现多个接口
abstract class A {
printA();
}
abstract class B {
printB();
}
class C implements A, B {
@override
printA() {}
@override
printB() {}
}
void main() {
C c = C();
c.printA;
c.printB;
runApp(const MyApp());
}
mixin 实现多继承
/*
mixin 不能有构造函数,必须继承自object
如果混入的两个类有相同方法名称,会执行混入后边那个
类型判断 c is A c is B c is C 都为true
*/
mixin class A {
String info = "this is info";
printA() {
print("A");
}
run() {
print("RunA");
}
}
mixin class B {
printB() {
print("B");
}
run() {
print("RunB");
}
}
class C with A, B {}
void main() {
C c = C();
c.printA();
c.printB();
c.run();
print(c.info);
//类型判断
if (c is A) {
print("is A");
}
if (c is B) {
print("is B");
}
if (c is C) {
print("is C");
}
runApp(const MyApp());
}