从Dart中的子类初始化最终字段

时间:2015-07-17 21:44:48

标签: dart

这不起作用:

abstract class Par {
  final int x;
}

class Sub extends Par {
  Sub(theX) {
    this.x = theX;
  }
}

我在Par中得到一个错误,说x必须初始化:

warning: The final variable 'x' must be initialized
warning: 'x' cannot be used as a setter, it is final

1 个答案:

答案 0 :(得分:2)

为超类提供构造函数,并使子类调用super

abstract class Par {
  final int x;
  Par (int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super(theX)
}

您可以将构造函数设为私有,因为methods and fields starting with _ are private in Dart

abstract class Par {
  final int x;
  Par._(int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super._(theX)
}
相关问题