14.9 Modifying the $print() method

BankAccount <- R6Class("BankAccount", list(
  owner = NULL,
  type = NULL,
  balance = 0,
  initialize = function(owner, type) {
    stopifnot(is.character(owner), length(owner) == 1)
    stopifnot(is.character(type), length(type) == 1)

    self$owner <- owner
    self$type <- type
  },
  deposit = function(amount) {
    self$balance <- self$balance + amount
    invisible(self)
  },
  withdraw = function(amount) {
    self$balance <- self$balance - amount
    invisible(self)
  },
  print = function(...) {
    cat("Account owner: ", self$owner, "\n", sep = "")
    cat("Account type: ", self$type, "\n", sep = "")
    cat("  Balance: ", self$balance, "\n", sep = "")
    invisible(self)
  }
))
  • Important point: Methods are bound to individual objects.
    • Reference semantics vs. copy-on-modify.
collinsavings

hadleychecking <- BankAccount$new("Hadley", type = "Checking")

hadleychecking