Skip to content

第7章:类与对象

7.1 面向对象核心概念

面向对象编程(OOP)是一种编程范式,它将数据和操作数据的方法封装在一起,形成对象。Dart 是一种面向对象的编程语言,支持类、对象、继承、封装、多态等面向对象编程特性。

核心概念

  • :定义了对象的属性和方法,是对象的蓝图
  • 对象:类的实例,具有类定义的属性和方法
  • 属性:对象的状态,存储数据
  • 方法:对象的行为,操作数据

7.2 类的定义

在 Dart 中,使用 class 关键字定义类:

基本语法

dart
class ClassName {
  // 属性
  // 方法
}

示例

dart
class Person {
  // 属性
  String name;
  int age;
  
  // 方法
  void sayHello() {
    print('Hello, my name is $name');
  }
  
  void celebrateBirthday() {
    age++;
    print('Happy birthday! I am now $age years old.');
  }
}

7.3 对象的创建与使用

使用 new 关键字创建对象(在 Dart 2.0+ 中,new 关键字是可选的):

示例

dart
void main() {
  // 创建对象
  Person person = Person();
  
  // 设置属性
  person.name = 'John';
  person.age = 30;
  
  // 调用方法
  person.sayHello(); // Hello, my name is John
  person.celebrateBirthday(); // Happy birthday! I am now 31 years old.
}

7.4 构造函数

构造函数用于初始化对象的属性。

默认构造函数

如果没有定义构造函数,Dart 会提供一个默认构造函数:

dart
class Person {
  String name;
  int age;
  
  // 默认构造函数(隐式)
  // Person();
}

自定义构造函数

dart
class Person {
  String name;
  int age;
  
  // 自定义构造函数
  Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

构造函数简写

Dart 提供了构造函数简写语法:

dart
class Person {
  String name;
  int age;
  
  // 构造函数简写
  Person(this.name, this.age);
}

命名构造函数

可以定义多个构造函数,使用不同的名称:

dart
class Person {
  String name;
  int age;
  
  // 主构造函数
  Person(this.name, this.age);
  
  // 命名构造函数
  Person.fromBirthYear(String name, int birthYear) {
    this.name = name;
    this.age = DateTime.now().year - birthYear;
  }
  
  // 命名构造函数
  Person.anonymous(int age) {
    this.name = 'Anonymous';
    this.age = age;
  }
}

使用命名构造函数

dart
void main() {
  // 使用主构造函数
  Person person1 = Person('John', 30);
  
  // 使用命名构造函数
  Person person2 = Person.fromBirthYear('Alice', 1990);
  Person person3 = Person.anonymous(25);
}

7.5 类的属性

实例属性

实例属性是对象的属性,每个对象都有自己的实例属性副本:

dart
class Person {
  // 实例属性
  String name;
  int age;
  
  Person(this.name, this.age);
}

静态属性

静态属性是类的属性,所有对象共享同一个静态属性:

dart
class Person {
  String name;
  int age;
  
  // 静态属性
  static int count = 0;
  
  Person(this.name, this.age) {
    count++;
  }
}

访问静态属性

dart
void main() {
  Person person1 = Person('John', 30);
  Person person2 = Person('Alice', 25);
  
  print('Person count: ${Person.count}'); // 2
}

7.6 类的方法

实例方法

实例方法是对象的方法,需要通过对象调用:

dart
class Person {
  String name;
  int age;
  
  Person(this.name, this.age);
  
  // 实例方法
  void sayHello() {
    print('Hello, my name is $name');
  }
}

静态方法

静态方法是类的方法,不需要创建对象就可以调用:

dart
class Person {
  String name;
  int age;
  
  Person(this.name, this.age);
  
  // 静态方法
  static void printMessage() {
    print('This is a static method');
  }
}

调用静态方法

dart
void main() {
  Person.printMessage(); // This is a static method
}

7.7 实操案例

定义类、创建对象,调用属性和方法实现简单功能

学生类示例

dart
class Student {
  // 属性
  String name;
  int age;
  String major;
  double gpa;
  
  // 构造函数
  Student(this.name, this.age, this.major, this.gpa);
  
  // 命名构造函数
  Student.fromMap(Map<String, dynamic> map) {
    name = map['name'];
    age = map['age'];
    major = map['major'];
    gpa = map['gpa'];
  }
  
  // 实例方法
  void study() {
    print('$name is studying $major');
  }
  
  void takeExam() {
    print('$name is taking an exam');
  }
  
  void showInfo() {
    print('Name: $name');
    print('Age: $age');
    print('Major: $major');
    print('GPA: $gpa');
  }
  
  // 静态方法
  static void printSchoolName() {
    print('XYZ University');
  }
}

void main() {
  // 调用静态方法
  Student.printSchoolName();
  
  // 创建对象
  Student student1 = Student('John', 20, 'Computer Science', 3.8);
  Student student2 = Student.fromMap({
    'name': 'Alice',
    'age': 19,
    'major': 'Mathematics',
    'gpa': 3.9
  });
  
  // 调用实例方法
  student1.showInfo();
  student1.study();
  
  print('\n');
  
  student2.showInfo();
  student2.takeExam();
}

运行结果

XYZ University
Name: John
Age: 20
Major: Computer Science
GPA: 3.8
John is studying Computer Science

Name: Alice
Age: 19
Major: Mathematics
GPA: 3.9
Alice is taking an exam

银行账户类示例

dart
class BankAccount {
  // 属性
  String accountNumber;
  String accountHolder;
  double balance;
  
  // 静态属性
  static double interestRate = 0.05;
  
  // 构造函数
  BankAccount(this.accountNumber, this.accountHolder, this.balance);
  
  // 实例方法
  void deposit(double amount) {
    balance += amount;
    print('Deposited $amount. New balance: $balance');
  }
  
  void withdraw(double amount) {
    if (amount <= balance) {
      balance -= amount;
      print('Withdrew $amount. New balance: $balance');
    } else {
      print('Insufficient balance');
    }
  }
  
  void calculateInterest() {
    double interest = balance * interestRate;
    balance += interest;
    print('Interest calculated: $interest. New balance: $balance');
  }
  
  void showInfo() {
    print('Account Number: $accountNumber');
    print('Account Holder: $accountHolder');
    print('Balance: $balance');
  }
}

void main() {
  // 创建银行账户
  BankAccount account = BankAccount('123456', 'John Doe', 1000.0);
  
  // 显示账户信息
  account.showInfo();
  
  // 存款
  account.deposit(500.0);
  
  // 取款
  account.withdraw(200.0);
  
  // 计算利息
  account.calculateInterest();
  
  // 显示最终账户信息
  account.showInfo();
}

运行结果

Account Number: 123456
Account Holder: John Doe
Balance: 1000.0
Deposited 500.0. New balance: 1500.0
Withdrew 200.0. New balance: 1300.0
Interest calculated: 65.0. New balance: 1365.0
Account Number: 123456
Account Holder: John Doe
Balance: 1365.0

© 2026 编程马·菜鸟教程 版权所有