如何在Dart中调用超类的构造函数和其他语句?

cor*_*ath 5 inheritance class dart

鉴于此代码:

abstract class Animal {

        String name;

        Animal (String this.name) {
        }

}

class Dog extends Animal {

        // Why does this fail
        Dog() {
            super("Spot");
            print("Dog was created");
        }

        // Compared to this
        // Dog() : super("Spot");

}
Run Code Online (Sandbox Code Playgroud)

根据多个文档:

您可以使用以下语法调用超类的构造函数:

Dog() : super("Spot");
Run Code Online (Sandbox Code Playgroud)

我假设这是一种快速调用超类构造函数的快捷语法.但是,如果我还想在Dog的构造函数中做更多的事情,例如调用,该怎么办print

为什么这不起作用,以及编写代码的正确方法是什么?

// Why does this fail
Dog() {
    super("Spot");
    print("Dog was created");
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*uli 11

你可以这样打电话super:

abstract class Animal {
  String name;
  Animal (String this.name);
}

class Dog extends Animal {
  Dog() : super('Spot') {
    print("Dog was created");
  }
}

void main() {
  var d = new Dog(); // Prints 'Dog was created'.
  print(d.name);     // Prints 'Spot'.
}
Run Code Online (Sandbox Code Playgroud)


Ern*_*ßer 7

如果你想在之前执行代码,super你可以这样做:

abstract class Animal {
  String name;
  Animal (this.name);
}

class Cat extends Animal {
  String breed;

  Cat(int i):
    breed = breedFromCode(i),
    super(randomName());

  static String breedFromCode(int i) {
    // ...
  }

  static String randomName() {
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*mer 5

在 Flutter (Dart) 中,如果我们有一个

class Bicycle {
  int gears;

  Bicycle(this.gears); // constructor
}
Run Code Online (Sandbox Code Playgroud)

和一个继承它的孩子

class ElectricBike extends Bicycle {
  int chargingTime;
}
Run Code Online (Sandbox Code Playgroud)

gears我们可以这样传递父构造函数输入参数:

class ElectricBike extends Bicycle {
  int chargingTime;

  
  ElectricBike(int gears, this.chargingTime) : super(gears);
}
Run Code Online (Sandbox Code Playgroud)

请注意使用: super(<parents parameters).