Skip to content

面向对象编程:继承与多态

继承

继承允许一个类从另一个类继承属性和方法。

dart
class Animal {
  String name;
  int age;
  
  Animal(this.name, this.age);
  
  void makeSound() {
    print('某种声音');
  }
  
  void eat() {
    print('$name 正在吃东西');
  }
}

class Dog extends Animal {
  String breed;
  
  Dog(String name, int age, this.breed) : super(name, age);
  
  @override
  void makeSound() {
    print('汪!汪!');
  }
  
  void fetch() {
    print('$name 正在捡球');
  }
}

void main() {
  var dog = Dog('Buddy', 3, '金毛');
  dog.makeSound();  // 汪!汪!
  dog.eat();        // Buddy 正在吃东西
  dog.fetch();      // Buddy 正在捡球
}

多态

dart
void animalSound(Animal animal) {
  animal.makeSound();
}

void main() {
  Animal animal = Animal('通用', 5);
  Dog dog = Dog('Buddy', 3, '拉布拉多');
  
  animalSound(animal);  // 某种声音
  animalSound(dog);     // 汪!汪!
}

方法重写

dart
class Shape {
  double area() => 0;
}

class Circle extends Shape {
  double radius;
  
  Circle(this.radius);
  
  @override
  double area() => 3.14159 * radius * radius;
}

class Rectangle extends Shape {
  double width, height;
  
  Rectangle(this.width, this.height);
  
  @override
  double area() => width * height;
}

Super 关键字

dart
class Vehicle {
  String brand;
  
  Vehicle(this.brand);
  
  void info() {
    print('品牌:$brand');
  }
}

class Car extends Vehicle {
  int doors;
  
  Car(String brand, this.doors) : super(brand);
  
  @override
  void info() {
    super.info();  // 调用父类方法
    print('车门数:$doors');
  }
}

下一步