14.1 Classes and methods
Q: Create a bank account R6 class that stores a balance and allows you to deposit and withdraw money. Create a subclass that throws an error if you attempt to go into overdraft. Create another subclass that allows you to go into overdraft, but charges you a fee.
Q: Create an R6 class that represents a shuffled deck of cards. You should be able to draw cards from the deck with
$draw(n), and return all cards to the deck and reshuffle with
$reshuffle(). Use the following code to make a vector of cards.
Q: Why can’t you model a bank account or a deck of cards with an S3 class?
Q: Create an R6 class that allows you to get and set the current timezone. You can access the current timezone with
Sys.timezone()and set it with
Sys.setenv(TZ = "newtimezone"). When setting the time zone, make sure the new time zone is in the list provided by
Q: Create an R6 class that manages the current working directory.It should have
Q: Why can’t you model the time zone or current working directory with an S3 class?
Q: What base type are R6 objects built on top of? What attributes do they have?
14.2 Controlling access
Q: Create a bank account class that prevents you from directly setting the account balance, but you can still withdraw from and deposit to. Throw an error if you attempt to go into overdraft.
Q: Create a class with a write-only
$passwordfield. It should have
$check_password(password)method that returns
FALSE, but there should be no way to view the complete password.
Q: Extend the
Randoclass with another active binding that allows you to access the previous random value. Ensure that active binding is the only way to access the value.
Q: Can subclasses access private fields/methods from their parent? Perform an experiment to find out.
14.3 Reference semantics
- Q: Create a class that allows you to write a line to a specified file. You should open a connection to the file in
$initialize(), append a line using
$append_line(), and close the connection in