Skip to content

面向对象编程:类与构造函数

Dart 是一种纯面向对象语言,一切皆对象。类是创建对象的蓝图。

基本类定义

dart
class Person {
  String name;
  int age;
  
  // 构造函数
  Person(this.name, this.age);
  
  // 方法
  void introduce() {
    print('嗨,我是 $name,今年 $age 岁。');
  }
}

void main() {
  Person person = Person('Alice', 25);
  person.introduce();  // 嗨,我是 Alice,今年 25 岁。
}

构造函数

默认构造函数

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

void main() {
  Point p = Point(10, 20);
}

命名构造函数

dart
class Point {
  double x, y;
  
  Point(this.x, this.y);
  
  // 命名构造函数
  Point.origin()
      : x = 0,
        y = 0;
  
  Point.fromJson(Map<String, double> json)
      : x = json['x']!,
        y = json['y']!;
}

void main() {
  Point p1 = Point(5, 10);
  Point p2 = Point.origin();
  Point p3 = Point.fromJson({'x': 3.0, 'y': 4.0});
}

初始化列表

dart
class Rectangle {
  double width, height, area;
  
  Rectangle(this.width, this.height)
      : area = width * height;
  
  Rectangle.square(double size)
      : width = size,
        height = size,
        area = size * size;
}

重定向构造函数

dart
class Point {
  double x, y;
  
  Point(this.x, this.y);
  
  // 重定向到主构造函数
  Point.alongXAxis(double x) : this(x, 0);
  Point.alongYAxis(double y) : this(0, y);
}

常量构造函数

dart
class ImmutablePoint {
  final double x, y;
  
  const ImmutablePoint(this.x, this.y);
}

void main() {
  const p1 = ImmutablePoint(1, 2);
  const p2 = ImmutablePoint(1, 2);
  
  print(identical(p1, p2));  // true(同一实例)
}

工厂构造函数

dart
class Logger {
  static final Map<String, Logger> _cache = {};
  final String name;
  
  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }
  
  Logger._internal(this.name);
  
  void log(String message) {
    print('[$name] $message');
  }
}

void main() {
  var logger1 = Logger('UI');
  var logger2 = Logger('UI');
  
  print(identical(logger1, logger2));  // true(同一实例)
}

属性

Getter 和 Setter

dart
class Rectangle {
  double width, height;
  
  Rectangle(this.width, this.height);
  
  // Getter
  double get area => width * height;
  
  // Setter
  set area(double value) {
    width = value / height;
  }
  
  double get perimeter => 2 * (width + height);
}

void main() {
  var rect = Rectangle(10, 5);
  print(rect.area);  // 50.0
  
  rect.area = 100;
  print(rect.width);  // 20.0
}

私有成员

使用下划线 _ 前缀表示私有成员:

dart
class BankAccount {
  String _accountNumber;
  double _balance;
  
  BankAccount(this._accountNumber, this._balance);
  
  double get balance => _balance;
  
  void deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
    }
  }
  
  bool withdraw(double amount) {
    if (amount > 0 && amount <= _balance) {
      _balance -= amount;
      return true;
    }
    return false;
  }
}

静态成员

dart
class MathUtils {
  static const double pi = 3.14159;
  static int callCount = 0;
  
  static double circleArea(double radius) {
    callCount++;
    return pi * radius * radius;
  }
}

void main() {
  print(MathUtils.pi);  // 3.14159
  print(MathUtils.circleArea(5));  // 78.53975
  print(MathUtils.callCount);  // 1
}

实例方法

dart
class Calculator {
  int add(int a, int b) => a + b;
  int subtract(int a, int b) => a - b;
  int multiply(int a, int b) => a * b;
  double divide(int a, int b) => a / b;
}

操作符重载

dart
class Vector {
  final double x, y;
  
  Vector(this.x, this.y);
  
  Vector operator +(Vector other) {
    return Vector(x + other.x, y + other.y);
  }
  
  Vector operator -(Vector other) {
    return Vector(x - other.x, y - other.y);
  }
  
  Vector operator *(double scalar) {
    return Vector(x * scalar, y * scalar);
  }
  
  @override
  bool operator ==(Object other) {
    return other is Vector && x == other.x && y == other.y;
  }
  
  @override
  int get hashCode => Object.hash(x, y);
  
  @override
  String toString() => 'Vector($x, $y)';
}

可调用类

dart
class Multiplier {
  final int factor;
  
  Multiplier(this.factor);
  
  int call(int value) => value * factor;
}

void main() {
  var triple = Multiplier(3);
  print(triple(5));  // 15
  print(triple.call(5));  // 15(相同)
}

完整示例

dart
class BankAccount {
  final String _accountNumber;
  String _holderName;
  double _balance;
  static int _totalAccounts = 0;
  
  // 构造函数
  BankAccount(this._accountNumber, this._holderName, [double initialBalance = 0])
      : _balance = initialBalance {
    _totalAccounts++;
  }
  
  // 命名构造函数
  BankAccount.savings(String accountNumber, String holderName)
      : this(accountNumber, holderName, 100);
  
  // Getter
  String get accountNumber => _accountNumber;
  String get holderName => _holderName;
  double get balance => _balance;
  
  // Setter
  set holderName(String name) {
    if (name.isNotEmpty) {
      _holderName = name;
    }
  }
  
  // 静态 getter
  static int get totalAccounts => _totalAccounts;
  
  // 方法
  void deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
      print('存款:¥$amount。新余额:¥$_balance');
    }
  }
  
  bool withdraw(double amount) {
    if (amount > 0 && amount <= _balance) {
      _balance -= amount;
      print('取款:¥$amount。新余额:¥$_balance');
      return true;
    }
    print('余额不足');
    return false;
  }
  
  void transfer(BankAccount recipient, double amount) {
    if (withdraw(amount)) {
      recipient.deposit(amount);
      print('转账 ¥$amount${recipient.accountNumber}');
    }
  }
  
  @override
  String toString() {
    return '账户:$_accountNumber,持有人:$_holderName,余额:¥$_balance';
  }
}

void main() {
  var account1 = BankAccount('ACC001', 'Alice', 1000);
  var account2 = BankAccount.savings('ACC002', 'Bob');
  
  print(account1);
  print(account2);
  
  account1.deposit(500);
  account1.withdraw(200);
  account1.transfer(account2, 300);
  
  print('\n最终余额:');
  print(account1);
  print(account2);
  
  print('\n总账户数:${BankAccount.totalAccounts}');
}

下一步