Dart 语言入门扫盲篇之5:【类】

469 阅读2分钟

【量】的修饰符

关键词:
·默认构造函数、命名构造函数、常量构造函数、工厂构造函数、初始化列表、重定向构造函数
·关键字: extends、abstract、implements、mixin、with、on、
·默认构造函数
无参构造函数,自动生成
class Point {
    num x, y;
    Point(); //编译时自动生成 默认构造函数
}
·命名构造函数
class Point {
    num x, y;
    Point(); //默认构造函数
    
    Point.origin() { 
    //命名构造函数, 作用是:在一个类中定义多个构造函数,或者让一个类的作用对于开发人员更清晰
        y = 0;
        x = 0;
    }
}
·常量构造函数
///作用:类生成的对象不会变化; 编译时常量
class ImmutablePoint {
    static final ImmutablePoint origin = const ImmutablePoint(x,0);

    final num x, y;
    const ImmutablePoint(this.x, this.y)
}
·工厂构造函数
在实现构造函数时使用factory关键字,该构造函数并不总是创建类的新实例。常用于 单例
class GiftCompleterManager {
  static GiftCompleterManager _manager = GiftCompleterManager._(); //常量
  
  GiftCompleterManager._(); //内部私有构造函数
  factory GiftCompleterManager() {
    return _manager;
  }
}
·初始化列表
作用拿传入的参数先做一步默认值的操作or计算
Point.fromJson(Map<String, num> json) : x = json['x'], y = json['y'] {
    print('In Point.fromJson():($x,$y)')
}
·重定向构造函数
///有点像Java的多参数构造函数,被重写
clsss Point {
    int x, y;
    Point(this.x, this.y);
    
    Point.redirect(int x) : this(x, 0);
}

注意

在Dart中,初始化的顺序如下:
1.执行initializer list;
2.执行父类的构造器;
3.执行子类的构造器。
·在【类】中使用到的关键字
extends、abstract、implements、mixin、with、on
·extends : 继承
·implements:实现
·abstract:抽象的,定义抽象类,or 接口
·mixin / with: Mixins 特性,相当于 android xml中的 include 特性,将mixin修饰的类给复用起来; 相当于多继承,
mixin Musical {
  bool canPlayPiano = false;
  bool canCompose = false;
  bool cannConduct = false;

  void entertainMe() {
    if (canPlayPiano) {
      print('playing piano');
    } else if (cannConduct) {
      print('waving hands');
    } else {
      print('Humming to self');
    }
  }
}

class Performer {}

///通过with关键字复用:
class Musician extends Performer with Musical {}

class Person {
  String length() {}
}

class Aggressive {
  String length() {}
}

class Demented {
  String length() {}
}

class Maestro extends Person with Musical, Aggressive, Demented {
  String name;
  bool canConduct;
  Maestro(String maestroName) {
    name = maestroName;
    canConduct = true;
  }
}

///通过 on 关键字实现继承的功能
mixin MusicalPerformer on Musician {
  // ···
}
·枚举
enum Color {
    red, green, blue
}

与 Java 不同的是: dart 的枚举类有一个 index 的getter,它是个连续的数字序列,从0开始:
assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);