Skip to content

Dart类和对象(Classes & Objects)

Dart 是一门纯粹的面向对象语言 —— 所有变量都是对象,每个对象都是某个类的实例。即使数字、函数、null 也是对象。

类定义了对象的成员变量(fields)方法(methods)


1. 定义一个类

dart
class Point {
  double x = 0;
  double y = 0;

  void printPoint() {
    print('($x, $y)');
  }
}
  • xy 是实例变量(成员变量)。
  • printPoint 是实例方法。
  • 默认情况下,实例变量会被初始化为 null,但如果启用了 null safety,你必须提供初始值,或用 late 声明延迟初始化。

2. 构造函数(Constructors)

构造函数的名字和类名相同:

dart
class Point {
  double x, y;

  // 默认构造函数
  Point(this.x, this.y);
}

上面的 this.x, this.y 是 Dart 的语法糖,等价于:

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

命名构造函数

可以定义多个构造函数:

dart
class Point {
  double x, y;

  Point(this.x, this.y);

  // 命名构造函数
  Point.origin() : x = 0, y = 0;
}

3. 初始化列表(Initializer list)

在构造函数体执行之前,可以用初始化列表设置实例变量:

dart
class Point {
  final double x;
  final double y;

  Point(double x, double y)
      : x = x,
        y = y {
    print('Point created ($x, $y)');
  }
}

4. 工厂构造函数(Factory constructors)

工厂构造函数不会总是创建新实例,它可以返回缓存的实例或者子类实例:

dart
class Logger {
  final String name;
  static final Map<String, Logger> _cache = {};

  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }

  Logger._internal(this.name);
}

5. Getter 和 Setter

Dart 默认会为实例变量提供 getter 和 setter。你也可以自定义:

dart
class Rectangle {
  double left, top, width, height;

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

  double get right => left + width;
  set right(double value) => left = value - width;

  double get bottom => top + height;
  set bottom(double value) => top = value - height;
}

6. 方法(Methods)

实例方法就是类中定义的函数:

dart
class Dog {
  void bark() {
    print('Woof!');
  }
}

操作符重载(Operator methods)

可以通过 operator 关键字重载运算符:

dart
class Vector {
  final int x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
}

7. 抽象类(Abstract classes)

抽象类不能被实例化,只能被继承或实现:

dart
abstract class Animal {
  void eat();
  void sleep() {
    print('Sleeping...');
  }
}

class Dog extends Animal {
  @override
  void eat() {
    print('Dog is eating');
  }
}

8. 隐式接口(Implicit interfaces)

Dart 中每个类都定义了一个隐式接口,其他类可以通过 implements 来实现:

dart
class Person {
  final String name;
  Person(this.name);

  void greet() => print('Hello, I am $name');
}

class Impostor implements Person {
  @override
  String get name => 'Impostor';

  @override
  void greet() => print('Hi, I am not really a person.');
}

9. 继承(Inheritance)

一个类只能继承自一个超类:

dart
class Animal {
  void breathe() => print('Breathing...');
}

class Bird extends Animal {
  void fly() => print('Flying...');
}

可以用 super 调用父类的构造函数或方法:

dart
class Mammal {
  String name;
  Mammal(this.name);
}

class Dog extends Mammal {
  Dog(String name) : super(name);
}

10. Mixins(混入)

Mixin 是一种代码复用方式,可以把多个类的特性“混入”另一个类:

dart
mixin Walker {
  void walk() => print('Walking...');
}

mixin Swimmer {
  void swim() => print('Swimming...');
}

class Human with Walker, Swimmer {}

11. 枚举(Enums)

枚举用来定义一组有限的常量值:

dart
enum Color { red, green, blue }

void main() {
  var c = Color.red;
  print(c); // Color.red
}

Dart 2.17 之后支持 增强枚举,可以在枚举中定义属性和方法:

dart
enum Planet {
  mercury(3.303e+23, 2.4397e6),
  earth(5.976e+24, 6.37814e6);

  final double mass; // 质量
  final double radius; // 半径

  const Planet(this.mass, this.radius);

  double get surfaceGravity => mass / (radius * radius);
}

12. 静态变量和方法

使用 static 声明静态变量或方法:

dart
class Circle {
  static const double pi = 3.14159;
  double radius;

  Circle(this.radius);

  static double area(double radius) => pi * radius * radius;
}