Dart语言零基础学习笔记(十八)
Dart多态
Datr中的多态:允许将子类类型的指针赋值给父类类型的指针, 同一个函数调用会有不同的执行效果 。
多态就是父类定义一个方法不去实现,让继承他的子类去实现,每个子类有不同的表现。
abstract class Animal {
eat();
}
class Cat extends Animal {
@override
eat() {
print("The cat is eating.");
}
}
class Dog extends Animal {
eat() {
print("The dog is eating.");
}
}
void main(List<String> args) {
Cat cat = new Cat();
Dog dog = new Dog();
cat.eat(); //The cat is eating.
dog.eat(); //The dog is eating.
}
子类的实例赋值给父类的引用
abstract class Animal {
eat();
}
class Cat extends Animal {
@override
eat() {
print("The cat is eating.");
}
run() {
print("running");
}
}
class Dog extends Animal {
eat() {
print("The dog is eating.");
}
run() {
print("running");
}
}
void main(List<String> args) {
Cat cat = new Cat();
cat.eat(); //The cat is eating.
cat.run();//running
/**定义子类里面只能实现父类的方法 */
Animal dog = new Dog();//将子类的实例赋值给父类的引用
dog.eat(); //The dog is eating.
/**不能再引用子类里面的自定义方法 */
dog.run();
}