跳到主要内容
文茂权 / DaftKen
返回

Dart-类成员的初始化

Dart 类成员的初始化

Dart 类成员的初始化有四种方式:

class Animal{
//   1. initialize at the declaration
  num age = 1;
//   2. assign variable in the constructor
  num leg;
  Animal(this.leg);
}

class Plant{
//   3. use the initialozer list
  num weight;
  num height;
  Plant(weight,height):this.weight = weight,this.height = height; 
}

class Human{
//   4. no-final variable can be initialize in the constructor. 
  final String name;
  num age;
  Human(name,age):this.name = name{
    this.age = age;
  }

//     The constructor below will casue a compile error because a final variable do not have a setter.
//     this.name = name;
//   Human(name,age){
//     this.age = age;
//     this.name = name;
//   }
  
}

void main (){
  Animal animal = new Animal(4);
  Plant plant = new Plant(1,2);
  Human human = new Human("Tom", 14);
}

在 DartPad 运行此代码

特别地 final 实例成员变量必须进行初始化,并且无法被赋值(这要求该成员需要一个 setter 方法)。因此 final 成员必须使用 前三种方式进行初始化。



上一篇
Dart-抽象方法、抽象类和接口
下一篇
Dart-命名构造函数