Dart中的类与对象

DartPad:https://dartpad.cn/

创建一个简单的 Dart类

定义类、构造函数及实例化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Bicycle {
int cadence;
int speed;
int gear;

Bicycle(this.cadence, this.speed, this.gear);

@override
String toString() => 'Bicycle: $speed mph';
}

void main() {
var bike = new Bicycle(2, 0, 1);
print(bike);
}

增加一个只读的变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Bicycle {
int cadence;
int _speed = 0; //所有名字以下划线开头的变量,Dart 的编译器都会将其强制标记为私有的;未初始化的变量(即使是数字类型的变量)的值都为 null
int get speed => _speed;
int gear;

Bicycle(this.cadence, this.gear);

void applyBrake(int decrement) {
_speed -= decrement;
}

void speedUp(int increment) {
_speed += increment;
}

@override
String toString() => 'Bicycle: $_speed mph';
}

void main() {
var bike = Bicycle(2, 1);
bike.speedUp(1);
print(bike);
}

使用可选参数

Dart 并不支持构造函数的重载,可以直接添加一个没有方法体的构造方法来替代 Java 代码中的四个构造方法。

1
Rectangle({this.origin = const Point(0, 0), this.width = 0, this.height = 0});

注:this.origin, this.width 和 this.height 嵌套在闭合的花括号中 ({}),用来表示是可选的命名参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import 'dart:math';

class Rectangle {
int width;
int height;
Point origin;

Rectangle({this.origin = const Point(0, 0), this.width = 0, this.height = 0});

@override
String toString() =>
'Origin: (${origin.x}, ${origin.y}), width: $width, height: $height';
}

main() {
print(Rectangle(origin: const Point(10, 20), width: 100, height: 200));
print(Rectangle(origin: const Point(10, 10)));
print(Rectangle(width: 200));
print(Rectangle());
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :