CSE116的学习笔记-Lec#8:Model of Execution live
Model of Execution
Live Examples
Lecture Question
Question: in a package named “execution”, implement the following classes:
Class Battery with:
- A constructor that takes a variable named “charge” of type Int
Class Flashlight with:
- A constructor that takes no parameters
- When a new Flashlight is created, declare a state variable named “battery” of type Battery and set it to a new Battery with 5 charge (ie. Batteries included)
- A method named “use” that takes no parameters and return Unit
- This method will decrease the charge of the Flashlight’s battery by 1
- If the charge of the battery is 0, this method does nothing
- A method named “replaceBattery” that takes a Battery as a parameter and returns a Battery
- This method swaps the inpit Battery with the Battery currently stored in this Flashlight’s state variable
- The returned Battery is the one that was in the state variable when the method is called
Testing: In a package named “tests” create a Scala class named “TestBatteries” as a test suite that tests all the functionality listed above. Be sure to check the references of batteries involved in both methods.
Checking References:
- When a battery is used, it is not enough to check that the charge of the battery in the flashlight has decreased by 1
- You must check the reference of the battery in the flashlight to ensure that it is in fact the same battery
- To do this, you should store a reference to the battery created when the flashlight was created so you can compare it to the reference in the flashlight after it’s used. The first thing you should do after creating a new flashlight is store a reference to its battery in a separate variable
1
2val f1: Flashlight = new Flashlight()
val f1Battery: Battery = f1.battery
- When replacing a battery, the batteries will be swapped by reference
- Be sure to check for the proper reference of the battery in the flashlight and the battery that is returned by the method for proper references
- Make sure the returned battery is the battery that was in the flashlight before the swap
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment
TwikooValine