[TOC]
Dart是一種面向對象的語言,具有類和基于mixin的繼承。每個對象都是一個類的實例,所有的類都是Object的子類。基于mixin的繼承意味著,盡管每個類(除了Object)都只有一個超類,但類主體可以在多個類層次結構中重用。
## 使用類成員
對象具有由函數和數據(分別是方法和實例變量)組成的成員。當您調用一個方法時,您在一個對象上調用它:該方式可以訪問該對象的函數和數據。
使用點號(.)引用實例變量或方法:
~~~
var p = Point(2, 2);
// Set the value of the instance variable y.
p.y = 3;
// Get the value of y.
assert(p.y == 3);
// Invoke distanceTo() on p.
num distance = p.distanceTo(Point(4, 4));
~~~
為避免最左操作數為空時出現異常,使用 ?.代替 .來使用:
~~~
// If p is non-null, set its y value to 4.
p?.y = 4;
~~~
## 使用構造函數
您可以使用構造函數創建一個對象。構造函數名可以是ClassName或ClassName.identifier。例如,以下代碼使用Point()和Point. fromjson()構造函數創建點對象:
~~~
var p1 = Point(2, 2);
var p2 = Point.fromJson({'x': 1, 'y': 2});
~~~
下面的代碼具有相同的效果,但是在構造函數名之前使用可選的new關鍵字:
~~~
var p1 = new Point(2, 2);
var p2 = new Point.fromJson({'x': 1, 'y': 2});
~~~
>版本注意事項:在Dart2中new關鍵字為可選關鍵字
>
有些類提供常量構造函數。要使用常量構造函數創建編譯時常量,請將const關鍵字放在構造函數名之前:
~~~
var p = const ImmutablePoint(2, 2);
~~~
構造兩個相同的編譯時常量會生成一個單一的、規范的實例:
~~~
var a = const ImmutablePoint(1, 1);
var b = const ImmutablePoint(1, 1);
assert(identical(a, b)); // They are the same instance!
~~~
在常量上下文中,可以在構造函數或文字之前省略const。例如,看看這個代碼,它創建了一個const的 map集合:
~~~
// Lots of const keywords here.
const pointAndLine = const {
'point': const [const ImmutablePoint(0, 0)],
'line': const [const ImmutablePoint(1, 10), const ImmutablePoint(-2, 11)],
};
~~~
除了第一次使用const關鍵字之外其他的const都可以省略:
~~~
// Only one const, which establishes the constant context.
const pointAndLine = {
'point': [ImmutablePoint(0, 0)],
'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)],
};
~~~
>版本說明:const關鍵字在Dart 2的常量上下文中變成可選的。
>
## 獲得對象的類型
要在運行時獲得對象類型,可以使用對象的runtimeType屬性,該屬性返回一個類型對象。
~~~
print('The type of a is ${a.runtimeType}');
~~~
到這里,您已經了解了如何使用類。本節的其余部分將展示如何實現類。
## 實例變量
下面是如何聲明實例變量的方法:
~~~
class Point {
num x; // Declare instance variable x, initially null.
num y; // Declare y, initially null.
num z = 0; // Declare z, initially 0.
}
~~~
所有未初始化的實例變量都具有null值。
所有實例變量都生成隱式getter方法。非最終實例變量也生成隱式setter方法。有關詳細信息,請參見[Getters和setters]。
~~~
class Point {
num x;
num y;
}
void main() {
var point = Point();
point.x = 4; // Use the setter method for x.
assert(point.x == 4); // Use the getter method for x.
assert(point.y == null); // Values default to null.
}
~~~
如果在聲明實例變量的地方(而不是在構造函數或方法中)初始化實例變量,則在創建實例時(在構造函數及其初始化列表執行之前)設置該值。