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

时间:2014-01-09 23:30:45

标签: class inheritance 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");

}

根据多个文档:

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

Dog() : super("Spot");

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

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

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

3 个答案:

答案 0 :(得分:8)

您可以通过以下方式致电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'.
}

答案 1 :(得分:0)

如果您想在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() {
    // ...
  }
}

答案 2 :(得分:0)

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

class Bicycle {
  int wheelsNumber;

  Bicycle(this.wheelsNumber); // constructor
}

和从中继承的孩子

class ElectricBike extends Bicycle {
  int chargingTime;

  // you can call on the super constructor as such
  ElectricBike(int wheelsNumber, this.chargingTime) : super(wheelsNumber);
}