Dart语言基础-类对象声明与构造
2019-08-05 本文已影响0人
柳源居士
- 类
基于mixin的继承机制,每个类都只能有一个父类。
每个对象都是一个类的实例,所有的类都继承于Object。
使用new 或者构造方法来创建一个对象。
构造方法:
-
default 构造方法:
与类名一致的构造方法。
如果不指定,则会生成一个没有参数的,并调用父类的没有参数的构造方法。 -
named 构造方法:
类名.构造方法名(参数){
构造内容
}
构造方法名应该清晰表明你的构造意图。 -
redirecting 构造方法:
重定向构造方法特征为没有具体实现,而是将实现重新定向到别的构造方法里。
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依赖于定位的构造方法。
- constant 构造方法:
所有变量都为final。
然后定义const 构造方法。
定义原点:
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);
- factory 构造方法:
使用关键字factory 来修饰构造方法。
特点:不总是返回一个新的实例。
如下例子:可以从catch中返回一个存在的实例,或者可以返回一个子类实例。
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);
}
}
注意点:
-
构造方法不能被子类继承,如果子类想使用同样的构造方法,必须自己实现。
子类如果没有定义构造函数,则只有一个默认构造函数 。 -
调用非默认的父类构造方法:
- 先调用初始化列表
同样使用 “ :”来初始化成员变量的值,各变量之间用“ ,”隔开。
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());
// ···
}
- const 常量
有些类提供constant constructor,可以通过constant 构造方法创造compile-time constant 常量,需要使用const 关键字标注在构造方法前面。
var p = const ImmutablePoint(2, 2);
语法糖:
- 使用this.x 参数来代替 参数名与类变量一致时的构造赋值。