Classes and Objects

11.1 Defining a Class

Privacy in Dart is library-level: identifiers starting with _ are private to their library (file), not to the class.

new is optional (and omitted in modern Dart).

class BankAccount {
  final String owner;               // public field
  double _balance;                  // private to the library (underscore prefix)
  static int _accountsCreated = 0;  // static (class-level)

  BankAccount(this.owner, [this._balance = 0]) {   // constructor with initializing formals
    _accountsCreated++;
  }

  double get balance => _balance;   // getter

  set balance(double value) {       // setter with validation
    if (value < 0) throw ArgumentError('Balance cannot be negative');
    _balance = value;
  }

  void deposit(double amount) {
    if (amount <= 0) throw ArgumentError.value(amount, 'amount', 'must be positive');
    _balance += amount;
  }

  bool withdraw(double amount) {
    if (amount > _balance) return false;
    _balance -= amount;
    return true;
  }

  static int get accountsCreated => _accountsCreated;

  @override
  String toString() => 'BankAccount($owner, \$${_balance.toStringAsFixed(2)})';
}

void main() {
  final acc = BankAccount('Ana', 100);
  acc.deposit(50);
  acc.withdraw(30);
  print(acc);                       // BankAccount(Ana, $120.00)
  print(BankAccount.accountsCreated);
}

11.2 Getters, Setters and Computed Properties

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

11.3 Static Members and Constants

class MathUtils {
  static const double goldenRatio = 1.618;
  static int square(int x) => x * x;
  MathUtils._();                    // private constructor: prevents instantiation
}
MathUtils.square(4);

11.4 The Object Class

Every class extends Object and gets toString(), ==, hashCode, runtimeType, and noSuchMethod(). Override toString, ==, and hashCode as needed (Module 22).