Dart语言基础-类对象声明与构造

2019-08-05  本文已影响0人  柳源居士

  1. 基于mixin的继承机制,每个类都只能有一个父类。
    每个对象都是一个类的实例,所有的类都继承于Object。
    使用new 或者构造方法来创建一个对象。

构造方法:

class Point {
  num x, y;

  // The main constructor for this class.
  Point(this.x, this.y);

  // Delegates to the main constructor.
  Point.alongXAxis(num x) : this(x, 0);
}

与named constructor的区别是named constructor有具体的实现,而redirecting constructor依赖于定位的构造方法。

class ImmutablePoint {
  static final ImmutablePoint origin =
      const ImmutablePoint(0, 0);

  final num x, y;

  const ImmutablePoint(this.x, this.y);
}

var a=const ImmutablePoint(1,1);
var b=const ImmutablePoint(2,1);
class Logger {
  final String name;
  bool mute = false;

  // _cache is library-private, thanks to
  // the _ in front of its name.
  static final Map<String, Logger> _cache =
      <String, Logger>{};

  factory Logger(String name) {
    if (_cache.containsKey(name)) {
      return _cache[name];
    } else {
      final logger = Logger._internal(name);
      _cache[name] = logger;
      return logger;
    }
  }

//named constructor
  Logger._internal(this.name);

  void log(String msg) {
    if (!mute) print(msg);
  }
}

注意点:

  1. 构造方法不能被子类继承,如果子类想使用同样的构造方法,必须自己实现。
    子类如果没有定义构造函数,则只有一个默认构造函数 。

  2. 调用非默认的父类构造方法:

class Point {
num x;
num y;

Point(this.x, this.y);

// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map jsonMap)
    : x = jsonMap['x'],
      y = jsonMap['y'] {
  print('In Point.fromJson(): ($x, $y)');
}
}

main() {
var pointA = new Point.fromJson({"x": 1, "y": 2});
}
//输出:In Point.fromJson(): (1, 2)

就是说,在父类的构造方法调用前,完成了对成员变量的赋值。


Because the arguments to the superclass constructor are evaluated before invoking the constructor, an argument can be an expression such as a function call:

class Employee extends Person {
  Employee() : super.fromJson(getDefaultData());
  // ···
}
  1. const 常量
    有些类提供constant constructor,可以通过constant 构造方法创造compile-time constant 常量,需要使用const 关键字标注在构造方法前面。
var p = const ImmutablePoint(2, 2);

语法糖:

  1. 使用this.x 参数来代替 参数名与类变量一致时的构造赋值。
上一篇 下一篇

猜你喜欢

热点阅读