闽公网安备 35020302035485号
Base Classes :Food 和 Animal System
// 基础Food层次结构
class Food {
finalString name;
finaldouble nutrients;
Food(this.name, this.nutrients);
}
class Meat extends Food {
finalbool isCooked;
Meat(String name, double nutrients, this.isCooked)
: super(name, nutrients);
}
class Vegetables extends Food {
finalbool isOrganic;
Vegetables(String name, double nutrients, this.isOrganic)
: super(name, nutrients);
}
Animal层次结构与covariant// Animal层次结构使用 covariant
abstractclass Animal {
void eat(covariant Food food);
Stringget species;
}
class Carnivore extends Animal {
@override
Stringget species => 'Carnivore';
@override
void eat(Meat food) {
if (!food.isCooked) {
print('$species is eating raw ${food.name}');
} else {
print('$species is eating cooked ${food.name}');
}
}
}
class Herbivore extends Animal {
@override
Stringget species => 'Herbivore';
@override
void eat(Vegetables food) {
if (food.isOrganic) {
print('$species is eating organic ${food.name}');
} else {
print('$species is eating non-organic ${food.name}');
}
}
}
用法示例和类型安全性演示void main() {
// 初始化Animal
final lion = Carnivore();
final rabbit = Herbivore();
// 初始化Food
final steak = Meat('Steak', 100, true);
final carrot = Vegetables('Carrot', 50, true);
final lettuce = Vegetables('Lettuce', 30, true);
final beef = Meat('Beef', 100, true);
// 直接使用正确的类型
lion.eat(steak); // ✅ "Carnivore is eating cooked Steak"
// lion.eat(carrot); // ❌ 编译时错误:错误的Food类型
rabbit.eat(lettuce); // ✅ "Herbivore is eating organic Lettuce"
// rabbit.eat(beef); // ❌ 编译时错误:错误的Food类型
// 使用基类引用
final Animal animal1 = Carnivore();
final Animal animal2 = Herbivore();
// animal1.eat(steak); // ❌ 需要类型检查
// animal2.eat(lettuce); // ❌ 需要类型检查
// 正确的类型检查
if (animal1 is Carnivore) {
animal1.eat(steak); // ✅ 类型检查后工作正常
}
if (animal2 is Herbivore) {
animal2.eat(lettuce); // ✅ 类型检查后工作正常
}
// 处理集合
List<Animal> animals = [lion, rabbit];
// 在集合中进行正确处理
animals.forEach((animal) {
if (animal is Carnivore) {
animal.eat(steak); // ✅ 类型安全
} elseif (animal is Herbivore) {
animal.eat(lettuce); // ✅ 类型安全
}
});
}
关键点5.记录预期的类型和行为。