Polymorphism of the Dart

  • It is possible to assign a pointer of a subclass type to a pointer of a superclass type. The same function call may have different execution effects.
  • An instance of a subclass is assigned to a reference to the parent class.
  • Polymorphism is when a parent class defines a method and does not implement it, leaving it to its descendants, each with a different implementation.
main(List<String> args) {
  var dog = newDog(); dog .. eat() .. run() .. sleep() .. printInfo(); Animal a =newDog(); a .. eat() .. run();/ /.. sleep(); //sleep() is created in a subclass and does not exist in the parent class.
  Animal c = newCat(); c .. eat() .. run();/ /.. sleep(); //sleep() is created in a subclass and does not exist in the parent class.
}

abstract class Animal {
  eat(); // Abstract methods
  run(); // Abstract methods
  printInfo() {
    print('Ordinary methods in abstract classes ~~'); }}class Dog extends Animal {
  @override
  eat() {
    // TODO: implement eat
    // throw UnimplementedError();
    print('Dog eats ~~');
  }

  @override
  run() {
    // TODO: implement run
    // throw UnimplementedError();
    print('The dog is running ~~');
  }

  sleep() {
    print('The dog is sleeping ~~'); }}class Cat extends Animal {
  @override
  eat() {
    // TODO: implement eat
    // throw UnimplementedError();
    print('Cat eats ~~');
  }

  @override
  run() {
    // TODO: implement run
    // throw UnimplementedError();
    print('The kitten is running.');
  }

  sleep() {
    print('The cat is sleeping.'); }}Copy the code