# 9.Dart中的类有何不同？

Dart 使用 class 来定义一个类。

# 定义一个类

``````class Point{
var x;
var y;

Point(x, y){
this.x = x;
this.y = y;
}
}

``````class Point{
var x;
var y;

Point(this.x, this.y);

Point.origin(){
x = 0;
y = 0;
}
}

var p = Point.origin();

`Point(this.x, this.y)` Dart 允许这样书写一个默认构造函数。

# 创建一个类对象

``````var p1 = Point(1, 1);
var p2 = new Point(1, 1);

Dart 同时支持以上两种创建一个类对象的方式。

`new` 关键字从 `Dart 2.0` 开始支持。

# 使用类的属性

``````var p1 = Point(1, 1);
print(p1.y);

>>>
1

p1.y = 5;
print(p1.y);

>>>
5

# 空安全 ?.

Dart 在调用对象属性前，支持先检查对象是否为 null。

``````var p;
p?.y = 5;

# 级联操作符 ..

``````querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.

Dart 支持使用 `..` 操作符编写如上的流式语句。

# 初始化列表

``````class Point {
final num x;
final num y;
final num distanceFromOrigin;

Point(x, y)
: x = x,
y = y,
distanceFromOrigin = sqrt(x * x + y * y);
}
import 'dart:math';
​
class Point {
final num x;
final num y;
final num distanceFromOrigin;
​
Point(x, y)
: x = x,
y = y,
distanceFromOrigin = sqrt(x * x + y * y);
}
​
main() {
var p = new Point(2, 3);
print(p.distanceFromOrigin);
}

>>>
3.605551275463989

# get/set 函数

``````class Rectangle {
num left, top, width, height;

Rectangle(this.left, this.top, this.width, this.height);

num get right => left + width;
set right(num value) => left = value - width;
num get bottom => top + height;
set bottom(num value) => top = value - height;
}

void main() {
var rect = Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
}

# 类型检测

``````var p = Point(1, 1);
print(p is Point);

>>>
true

`is!` 恰好于此相反。

# 类型转换

Dart 使用 `as` 关键字来进行强制类型转换。

``````(emp as Person).firstName = 'Bob';

# 获得对象的运行时类型

``print('The type of a is \${a.runtimeType}');复制代码``